在Elasticsearch Python DSL中使用瓦片和模糊性?

exdqitrt  于 2023-02-03  发布在  ElasticSearch
关注(0)|答案(2)|浏览(136)

如何调用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'])]))
9fkzdhlc

9fkzdhlc1#

要使用shingle,你需要在Map中定义它们,现在尝试在查询时使用它们已经太晚了,在查询时你只能使用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查询。
希望这个有用。

chhqkbe1

chhqkbe12#

截至2023年1月:elasticsearch-dsl确实支持模糊匹配,但它只是没有很好地记录下来。

对于简单模糊匹配:

Q('fuzzy', fieldName=matchString)

如果要设置自定义模糊度:

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

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

资料来源

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

相关问题