假设我有一个代表如下博客文章的 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。
如何筛选去年同月及以后发布的文档?例如,如果是 2024 年 5 月,我想获取 2023 年 5 月、2022 年 5 月等发布的文档
结合使用
greater than or equal
和 less than
运算符以及表示所需月份开始和结束的特定日期值。
Azure AI Search 不提供像
month()
这样的内置函数来直接提取月份部分。
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)
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 月发布的所有文档。