python - Elasticsearch DSL 过滤器

标签 python django elasticsearch elasticsearch-dsl

我的 Elasticsearch 过滤器有问题。我正在尝试使用 Elasticsearch DSL 过滤器搜索文本,但我遇到了排序问题。

搜索文字: Hello World

文档中的其他字符串:你好, Hello World ,你好大家,你好你好 , ETC...

Elasticsearch-dsl 查询是:

MyDocument.search().filter(Q("match", title="hello world") | Q("match", original_title="hello world")).execute()

Elasticsearch 查询是这样的:
{
    'bool': {
        'filter': [{
            'bool': {
                'should': [{
                    'match': {
                        'title': 'hello world'
                    }
                }, {
                    'match': {
                        'original_title': 'hello world'
                    }
                }]
            }
        }]
    }
}

输出类似于 大家好,你好,世界你好 , ETC..

但我想要 Hello World 第一的。

提前致谢!

最佳答案

从您的查询中,您似乎希望从多个字段中搜索相同的标记。

当然@jaspreet 提到了你想要的答案,但是如果你想简化你的查询(当然Bool Queries 也很简单),那么你可以使用query_string如下:

POST <your_index_name>/_search
{
  "query": {
    "query_string": {
      "fields": ["title", "original_title"], 
      "query": "hello world",
      "default_operator": "OR"
    }
  }
}

您也可以使用 multi-match查询以简化您的查询,如下所示:
POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "hello world",
            "fields": ["title", "original_title"],
            "operator": "OR"
          }
        }
      ]
    }
  }
}

在这两种用例中,您都会得到想要的结果。

当然,您需要对其进行测试,看看响应是如何出现的,以及使用这些可以解决哪些用例。

注:只是基于@Val 评论的附加说明,您也可以使用simple query string而不是 query_string如果输入来自用户,这与 query_string 不同不会为无效语法抛出任何错误。

希望这可以帮助!

关于python - Elasticsearch DSL 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60648909/

相关文章:

python - 如果字符串不等于值则删除行 - Pandas

django 如何在更新用户时发送 post_save 信号?

热门点击的 ElasticSearch 聚合

docker - 如何在 Docker 内的 M1 (ARM) 上运行 ElasticSearch v6

python - 使用 Python unittest 模拟 side_effect

python - 从 Tkinter 中的 askopenfilename 函数获取文件路径

python - 在间隔列表上自定义 pandas groupby

python - Django:过滤器()不返回任何东西

python - Django 响应没有内容 - 如何调试?

regex - 监控 http 响应内容正则表达式行为