在Elasticsearch Python DSL中使用带状疱疹和模糊性



您如何在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'])]))

要使用带状疱疹在映射中定义它们,为时已晚,在查询时间尝试使用它们为时已晚。在查询时间,您可以做的是使用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查询。

希望这会有所帮助。

截至2023年1月,:elasticsearch-dsl确实支持模糊匹配,但它的记录不是很好。

对于简单的模糊匹配:

Q('fuzzy', fieldName=matchString)

当您要设置自定义模糊时:

Q({"fuzzy": {"yourFieldName": {"value": matchString, "fuzziness": fuzziness}}})

我的理解是,fuzzy关键字只是标准查询的包装器,请参见https://github.com/elastic/elasticsearch-dsl-py/blob/blob/master/master/master/elasticsearch_dsl/query.py.py.py.py.py#l362.

  1. https://github.com/elastic/elasticsearch-dsl-py/issues/1510(github上的@leberknecht提供)

最新更新