我有多个文件的索引。这些文档包含以下字段:
我想创建一个elasticsearch dsl查询。对于此查询,有两个输入可用,例如adhar_number和pan_number。此查询应匹配或与此相关的条件。
示例:如果一个文档仅包含提供的adhar_number,那么我也希望该文档。
我有一本字典,其中包含以下内容(my_dict):
{
"adhar_number": "123456789012",
"pan_number": "BGPPG4315B"
}
我尝试如下:
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
s = Search(using=es, index="my_index")
for key, value in my_dict.items():
s = s.query("match", **{key:value})
print(s.to_dict())
response = s.execute()
print(response.to_dict())
它创建以下查询:
{
'query': {
'bool': {
'must': [
{
'match': {
'adhar_number': '123456789012'
}
},
{
'match': {
'pan_number': 'BGPPG4315B'
}
}
]
}
}
}
上面的代码为我提供了带有 AND条件而不是或Condition 的结果。
请给我建议包括OR条件的好建议。
最佳答案
要修复ES查询本身,您所需要做的就是使用“应该”而不是“必须”:
{
'query': {
'bool': {
'should': [
{
'match': {
'adhar_number': '123456789012'
}
},
{
'match': {
'pan_number': 'BGPPG4315B'
}
}
]
}
}
}
要在python中实现此目的,请参见the docs中的以下示例。默认逻辑为AND,但是您可以将其替代为OR,如下所示。
Query combination Query objects can be combined using logical operators:
Q("match", title='python') | Q("match", title='django') # {"bool": {"should": [...]}} Q("match", title='python') & Q("match", title='django') # {"bool": {"must": [...]}} ~Q("match", title="python") # {"bool": {"must_not": [...]}}
When you call the .query() method multiple times, the & operator will be used internally:
s = s.query().query() print(s.to_dict()) # {"query": {"bool": {...}}}
If you want to have precise control over the query form, use the Q shortcut to directly construct the combined query:
q = Q('bool', must=[Q('match', title='python')], should=[Q(...), Q(...)], minimum_should_match=1 ) s = Search().query(q)
所以你想要像
q = Q('bool', should=[Q('match', **{key:value})])
关于python-3.x - Elasticsearch DSL或查询格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401975/