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

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

如何称呼 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/

相关文章:

python - 如何使用 fbs 在 PyQt 样式表中引用资源文件

java - 如何使用 JOOQ 或任何其他库使用以下数据构建方言敏感的 SQL 查询?

java - 如何让 QueryDSL 动态从 QClass 获取路径的字段类型?

java - Spring Boot 1.5.13 - QueryDSL 查询 ClassNotFoundException?

java - 如果值不存在则更新的 ElasticSearch 脚本

python - 如何在不使用 pyCURL 的情况下获取信息(请求)

javascript - django javascript 不工作

python - 寻找 "decent"数字算法推理?

elasticsearch - ElasticSearch将嵌套字段重新索引为新文档

elasticsearch - 将字段设置为在Elasticsearch 1.7的索引下的所有( future )类型中为not_analysed