【问题标题】:combine terms and bool query in elasticsearch在弹性搜索中结合术语和布尔查询
【发布时间】:2020-12-24 10:33:44
【问题描述】:

我想在弹性搜索索引中进行搜索,但只搜索 id 列表。我可以使用术语查询来选择 ID

{
    "query": {
        "terms": {
            "_id": list_of_ids
        }
    }
}

现在我想在结果列表中搜索,可以通过这样的查询来完成

{
    "query": {
        "bool": {
            "must": {}
        }
    }
}

我的问题是如何结合这两个查询? 我发现的一种解决方案是像这样将 id 添加到必须查询中

{
    "query": {
        "bool": {
            "must": {}
            "should": [{
                "term": {
                    "_id": id1
                },
                "term": {
                    "_id": id2
                }]
            }
        }
    }
}

效果很好。但是,如果 id 列表非常大,可能会导致错误。

elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'failed to create query:

我想知道是否有更紧凑的方式来编写这样的查询?我认为上面的错误是由于我的查询太长了,因为我添加了数千个术语搜索......必须有一种方法来提供一个数组,就像在术语查询中一样?

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    解决了

    {
        "query": {
            "bool": {
                "must": {},
                "filter": {
                    "terms": {
                        "_id": list_of_ids
                    }
                }
            }
        }
    }
    

    对不起,我是 elasticsearch 的新手...

    【讨论】:

      【解决方案2】:

      您也可以使用IDs query,它根据文档的 ID 返回文档。

      添加一个包含索引数据、搜索查询和搜索结果的工作示例。

      索引数据:

      {
          "name":"buiscuit",
          "cost":"55",
          "discount":"20"
      }
      {
          "name":"multi grain bread",
          "cost":"55",
          "discount":"20"
      }
      

      搜索查询:

      {
        "query": {
          "bool": {
            "must": {
              "match": {
                "name": "bread"
              }
            },
            "filter": {
              "ids": {
                "values": [
                  "1",
                  "2",
                  "4"
                ]
              }
            }
          }
        }
      }
      

      搜索结果:

      "hits": [
            {
              "_index": "65431114",
              "_type": "_doc",
              "_id": "1",
              "_score": 0.5754429,
              "_source": {
                "name": "multi grain bread",
                "cost": "55",
                "discount": "20"
              }
            }
          ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 2017-06-09
        • 2016-03-10
        • 1970-01-01
        • 2014-06-02
        • 2015-08-15
        相关资源
        最近更新 更多