Azure AI 搜索:按月过滤 DateTimeOffset 字段

问题描述 投票:0回答:1

假设我有一个代表如下博客文章的 Azure AI 搜索索引定义。 (为了简洁起见,进行了简化)

id: String
title: String
posted_at: DateTimeOffset

如何筛选去年同月及以后发布的文档? 例如,如果是 2024 年 5 月,我想获取 2023 年 5 月、2022 年 5 月等发布的文档

我正在寻找类似于本页中描述的month()函数的东西( https://learn.microsoft.com/en-us/odata/webapi/date-and-timeofday-support#query-examples) 但它在 AI 搜索中不可用。

azure.core.exceptions.HttpResponseError: () Invalid expression: Function 'month' is not supported.

我目前正在使用Python SDK搜索API。

https://learn.microsoft.com/en-us/python/api/azure-search-documents/azure.search.documents.searchclient?view=azure-python#azure-search-documents-searchclient-search

azure odata azure-ai-search
1个回答
0
投票

如何筛选去年同月及以后发布的文档?例如,如果是 2024 年 5 月,我想获取 2023 年 5 月、2022 年 5 月等发布的文档

结合使用

greater than or equal
less than
运算符以及表示所需月份开始和结束的特定日期值。

  1. 确定所需月份的开始日期和结束日期。
  2. 构造一个过滤表达式,将 DateTimeOffset 字段与这些日期进行比较。

我正在寻找类似于本页()中描述的month()函数的东西,但它在AI搜索中不可用。

Azure AI Search 不提供像

month()
这样的内置函数来直接提取月份部分。

  • 要使用 Azure Python SDK 以编程方式获取此信息,请检查以下代码。
from azure.search.documents import SearchClient
from datetime import datetime, timedelta

# Define your Azure Search endpoint and key
endpoint = "YOUR_SEARCH_ENDPOINT"
key = "YOUR_SEARCH_KEY"
index_name = "YOUR_INDEX_NAME"

# Create a SearchClient
client = SearchClient(endpoint=endpoint, index_name=index_name, credential=key)

# Define the current month and year
current_month = datetime.now().month
current_year = datetime.now().year

# Calculate start and end dates for the desired month
start_date = datetime(current_year, current_month, 1)
end_date = start_date + timedelta(days=32)  # Adding 32 days to cover the entire month

# Format dates as strings
start_date_str = start_date.strftime('%Y-%m-%dT00:00:00Z')
end_date_str = end_date.strftime('%Y-%m-%dT00:00:00Z')

# Construct filter expression
filter_expression = f"posted_at ge {start_date_str} and posted_at lt {end_date_str}"

# Execute the search query with the constructed filter expression
results = client.search(search_text="*", filter=filter_expression)

# Process and display search results
for result in results:
    print(result)
  • 使用过滤表达式检索 2023 年 5 月发布的文档。
filter=posted_at ge 2023-05-01T00:00:00Z and posted_at lt 2023-06-01T00:00:00Z

posted_at ge 2023-05-01T00:00:00Z
检查文档是否在 2023 年 5 月 1 日或之后发布。

posted_at lt 2023-06-01T00:00:00Z
检查文档是否在 2023 年 6 月 1 日之前发布,实际上包括 2023 年 5 月发布的所有文档。

© www.soinside.com 2019 - 2024. All rights reserved.