按日期筛选和排序

    在本指南中,您将了解 Meilisearch 处理日期和时间值的方法、如何准备数据集以进行索引,以及如何按时间顺序对搜索结果进行排序和筛选。

    准备您的文档

    要按时间顺序筛选和排序搜索结果,您的文档必须至少有一个包含 UNIX 时间戳 的数字字段。

    例如,考虑一个视频游戏数据库。在此数据集中,发布年份被格式化为时间戳

    [
      {
        "id": 0,
        "title": "Return of the Obra Dinn",
        "genre": "adventure",
        "release_timestamp": 1538949600
      },
      {
        "id": 1,
        "title": "The Excavation of Hob's Barrow",
        "genre": "adventure",
        "release_timestamp": 1664316000
      },
      {
        "id": 2,
        "title": "Bayonetta 2",
        "genre": "action",
        "release_timestamp": 1411164000
      }
    ]
    

    如果您的日期字段以数字时间戳以外的格式表示,例如 ISO 8601,您必须在用 Meilisearch 索引之前对其进行转换。

    大多数编程语言都有内置工具来帮助您完成此过程。下面的 JavaScript 示例将游戏的发布日期 "2018-10-18" 转换为数字时间戳

    let game = {
      "id": 0,
      "title": "Return of the Obra Dinn",
      "genre": "adventure",
      "release_date": "2018-10-18T00:00Z"
    };
    
    const timestampInMilliseconds = Date.parse(game.release_date); // Date.parse returns the timestamp in milliseconds
    const timestamp = timestampInMilliseconds / 1000; // UNIX timestamps must be in seconds
    
    game = {
      "id": 0,
      "title": "Return of the Obra Dinn",
      "genre": "adventure",
      "release_date": "2018-10-18T00:00Z",
      "release_timestamp": timestamp
    };
    
    提示

    准备数据集时,将原始日期和时间字段完整地保留在文档中可能很有用。在上面的示例中,我们保留 release_date 字段,因为它比原始的 release_timestamp 更易读。

    在将数字时间戳添加到所有文档后,像往常一样索引您的数据。下面的示例将一个 视频游戏数据集 添加到一个 games 索引

    curl \
      -x POST 'MEILISEARCH_URL/indexes/games/documents' \
      -h 'content-type: application/json' \
      --data-binary @games.json

    按时间戳筛选

    要根据搜索结果的时间戳进行筛选,请将文档的时间戳字段添加到 filterableAttributes 列表中

    curl \
      -X PUT 'MEILISEARCH_URL/indexes/games/settings/filterable-attributes' \
      -H 'Content-Type: application/json' \
      --data-binary '[
        "release_timestamp"
      ]'

    配置 filterableAttributes 后,您可以按日期筛选搜索结果。以下查询仅返回 2018 年至 2022 年之间发布的游戏

    curl \
      -X POST 'MEILISEARCH_URL/indexes/games/search' \
      -H 'Content-Type: application/json' \
      --data-binary '{
        "q": "",
        "filter": "release_timestamp >= 1514761200 AND release_timestamp < 1672527600"
      }'

    按时间戳排序

    要按时间顺序对搜索结果进行排序,请将文档的时间戳字段添加到 sortableAttributes 列表中

    curl \
      -X PUT 'MEILISEARCH_URL/indexes/games/settings/sortable-attributes' \
      -H 'Content-Type: application/json' \
      --data-binary '[
        "release_timestamp"
      ]'

    配置 sortableAttributes 后,您可以根据搜索结果的时间戳对其进行排序。以下查询返回所有游戏,从最新到最旧排序

    curl \
      -X POST 'MEILISEARCH_URL/indexes/games/search' \
      -H 'Content-Type: application/json' \
      --data-binary '{
        "q": "",
        "sort": ["release_timestamp:desc"]
      }'