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

Using shingles and fuzziness in Elasticsearch Python DSL?

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

这是一个简单的示例,它在 "name" 字段中搜索一个短语,在 "surname" 字段中搜索另一个短语。

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 查询。

希望对您有所帮助。