gpt4 book ai didi

python - 使用Python进行Elasticsearch多重查询/搜索

转载 作者:行者123 更新时间:2023-12-03 02:13:35 25 4
gpt4 key购买 nike

我是Python和Elasticsearch的新手,我已经在Elasticsearch中创建了一个包含一些数据的索引,我想基于Python从用户那里收到的一些过滤器对它们执行查询(关键字,类别)

from elasticsearch import Elasticsearch
import json,requests

es = Elasticsearch(HOST="http://localhost", PORT=9200)
es = Elasticsearch()

def QueryMaker (keyword,category):
response = es.search(index="main-news-test-data",body={"from":0,"size":10000,"query":{
"bool": {
"should": [
{
"multi_match" : {
"query": keyword,
"fields": [ "content", "title","lead" ]
}
},
{
"multi_match" : {
"query": category,
"fields": [ "category" ]
}
}
]
}
}})
return(response)

def Mapper (category):
fhandle = open('categories.txt','r', encoding="utf8")
for line in fhandle:
line = line.rstrip()
items = line.split(';')
if f'"{category}"' in items:
category = items[0]
return(category)

if __name__ == '__main__':
keyword = input('Enter Keyword: ')
print(type(keyword))
category = input('Enter Category: ')
print(type(category))
#startDate = input('Enter StartDate: ')
#endDate = input('Enter EndDate: ')

mapCategory = Mapper(category)
if mapCategory is not None:
mapCategory = mapCategory.replace("%","")
data = QueryMaker(keyword,mapCategory)
print(data)
else:
data = QueryMaker(keyword,mapCategory)
print(data)
问题在于该程序仅在2个字段已满的情况下才返回匹配的数据,但如果1个字段(如category)为空,我也希望它也返回数据。当关键字为空时,类似“”,并且不返回任何内容;当类别为空时,我收到此错误:
elasticsearch.exceptions.RequestError: RequestError(400, 'x_content_parse_exception', '[multi_match] unknown token [VALUE_NULL] after [query]')   
我在做什么错,如何解决我的搜索过滤器?

最佳答案

添加带有索引数据,搜索查询和搜索结果的工作示例
根据上述评论,如果content字段不包含keyword,并且如果category字段包含category,则将对category字段执行搜索查询。这可以通过使用 minimum_should_match 来实现
索引数据:

{
"content": "keyword a",
"title": "b",
"lead": "c",
"category": "d"
}
{
"content": "a",
"title": "b",
"lead": "c",
"category": "category"
}
{
"content": "keyword a",
"title": "b",
"lead": "c",
"category": "category"
}
搜索查询:
{
"query": {
"bool": {
"should": [
{
"multi_match": {
"query": "keyword",
"fields": [
"content",
"title",
"lead"
]
}
},
{
"multi_match": {
"query": "category",
"fields": [
"category"
]
}
}
],
"minimum_should_match":1
}
}
}
搜索结果:
"hits": [
{
"_index": "stof_64081587",
"_type": "_doc",
"_id": "3",
"_score": 0.9666445,
"_source": {
"content": "keyword a",
"title": "b",
"lead": "c",
"category": "category"
}
},
{
"_index": "stof_64081587",
"_type": "_doc",
"_id": "2",
"_score": 0.60996956,
"_source": {
"content": "keyword a",
"title": "b",
"lead": "c",
"category": "d"
}
},
{
"_index": "stof_64081587",
"_type": "_doc",
"_id": "1",
"_score": 0.35667494,
"_source": {
"content": "a",
"title": "b",
"lead": "c",
"category": "category"
}
}
]

关于python - 使用Python进行Elasticsearch多重查询/搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64081587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com