【问题标题】:Using shingles and fuzziness in Elasticsearch Python DSL?在 Elasticsearch Python DSL 中使用带状疱疹和模糊性?
【发布时间】:2017-07-06 21:37:33
【问题描述】:

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'])]))

【问题讨论】:

    标签: python elasticsearch querydsl elasticsearch-dsl elasticsearch-dsl-py


    【解决方案1】:

    要使用 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 查询。

    希望这会有所帮助。

    【讨论】:

    • 非常感谢。不过,我该如何去允许模糊性呢?现在,我刚刚制作了一个包含模糊搜索所需查询的字典,并使用 Q({...}) 将其转换为 Q 对象。有没有更好的方法将参数传递给查询?源代码表明查询不允许任何附加参数。
    • 当然,Q("match", name__shingles={'query': fields['name'], 'fuzziness': 'AUTO'}) 应该可以正常工作 - kwargs 本质上只是生成的 json 中的键。
    猜你喜欢
    • 2017-07-13
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多