在本指南中,您将了解 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"]
  }'