gpt4 book ai didi

python - 在 Elasticsearch Python DSL 中使用 shingles 和模糊性?

转载 作者:行者123 更新时间:2023-12-01 03:17:58 25 4
gpt4 key购买 nike

如何称呼 Python DSL 中的带状疱疹?

这是一个简单的示例,在“姓名”字段中搜索一个短语,在“姓氏”字段中搜索另一个短语。

import json
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

def make_dsl_query(fields):
"""
Construct a query
"""
es_client = Elasticsearch()
my_query = Search(using=es_client, index="my_index", doc_type="my_type")

if fields['name'] and fields['surname']:
my_query = my_query.query(Q('bool', should=
[Q("match", name=fields['name']),
Q("match", surname=fields['surname'])]))
return my_query


if __name__ == '__main__':

my_query = make_dsl_query(fields={"name": "Ivan The Terrible", "surname": "Conqueror of the World"})
response = my_query.execute()

# print response
for hit in response:
print(hit.meta.score, hit.name, hit.surname)

1) 可以使用木瓦吗?如何?我尝试了很多方法,但在文档中找不到任何内容。

这可以在普通的 Elasticsearch 查询中工作,但显然在 Python DSL 中以不同的方式调用......

my_query = my_query.query(Q('bool', should=
[Q("match", name.shingles=fields['name']),
Q("match", surname.shingles=fields['surname'])]))

2) 如何将模糊参数传递给我的匹配?似乎也找不到任何东西。理想情况下我能够做这样的事情:

my_query = my_query.query(Q('bool', should=
[Q("match", name=fields['name'], fuzziness="AUTO", max_expansions=10),
Q("match", surname=fields['surname'])]))

最佳答案

要使用 shingles,您需要在映射中定义它们,现在尝试在查询时使用它们为时已晚。在查询时,您可以使用 match_phrase 查询。

my_query = my_query.query(Q('bool', should=
[Q("match", name.shingles=fields['name']),
Q("match", surname.shingles=fields['surname'])]))

如果写成这样应该可以工作:

 my_query = my_query.query(Q('bool', should=
[Q("match", name__shingles=fields['name']),
Q("match", surname__shingles=fields['surname'])]))

假设您在 namesurname 字段上定义了 shingles 字段。

请注意,您还可以使用 | 运算符:

 my_query = Q("match", name__shingles=fields['name']) | Q("match", surname.shingles=fields['surname'])

而不是自己构建 bool 查询。

希望这有帮助。

关于python - 在 Elasticsearch Python DSL 中使用 shingles 和模糊性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42296597/

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