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

准备您的文档

若要按时间顺序筛选和排序搜索结果,您的文档必须至少有一个包含 UNIX 时间戳的字段。您也可以使用带有可按字典顺序排序的日期格式的字符串,例如 "2025-01-13" 例如,考虑一个视频游戏数据库。在该数据集中,发布年份格式为时间戳:
[
  {
    "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
  }
]
一旦数据集中的所有文档都具有日期字段,请照常索引您的数据。以下示例将视频游戏数据集添加到 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"]
  }'
© . This site is unofficial and not affiliated with Meilisearch.