【问题标题】:How to filter with multiple fields and values in elasticsearch?如何在elasticsearch中过滤多个字段和值?
【发布时间】:2018-07-14 19:25:38
【问题描述】:

我一直在阅读文档并试图实现通过多个字段和列过滤结果的解决方案,但是我不断收到错误; 格式错误的查询

我想用完全相同的值过滤结果,例如:

is_active: true
category_id: [1,2,3,4]
brand: "addidas"
gender: "male"

为了更清楚地说明我打算做什么,如果它是用 SQL 编写的,我希望它是这样运行的:

SELECT .... WHERE 
is_active= 1 AND category_id IN(1,2,3,4) 
AND brand='addidas' AND gender='male'

我在 DSL 中的查询如下:

{
    "body": {
        "query": {
            "nested": {
                "query": {
                    "bool": {
                        "must": {
                            "terms": {
                                "category_id": [
                                    1,
                                    2,
                                    3
                                ]
                            },
                            "term": {
                                "is_active": true
                            },
                            "term": {
                                "brand": "addidas"
                            }
                        }
                    }
                }
            }
        }
    }
}

如何在 elasticsearch 中按照描述过滤多个字段和值?

如果您需要我回答问题所需的额外信息,请发表评论。如果您添加文档链接,还请提供一个示例(使用查询 dsl)说明如何我目前或类似的情况应该得到解决。

【问题讨论】:

  • 请显示您遇到的完整错误以及您需要匹配的示例文档。另外我认为解决方案可能是简单地删除nested 查询。
  • @Kilise,请添加在 elasticsearch 中索引的文档示例

标签: elasticsearch querydsl


【解决方案1】:

使用以下代码:

子句(查询)必须出现在匹配的文档中,并且会影响分数。

"query": {
    "bool": {
        "must" : [
            {"term" : { "is_active" : true}},
            {"term" : { "gender" : "female"}},
            {"term" : { "brand" : "addidas"}},
            {"terms": { "categoryId": [1,2,3,4]}}
        ]
    }
}

在过滤器元素下指定的查询对评分没有影响

"query": {
    "bool": {
        "filter" : [
            {"term" : { "is_active" : true}},
            {"term" : { "gender" : "female"}},
            {"term" : { "brand" : "addidas"}},
            {"terms": { "categoryId": [1,2,3,4]}}
        ]
    }
}

【讨论】:

  • 谢谢,这很完美。即使在阅读文档时,也很难弄清楚物体的位置。谢谢!
  • 这根本不起作用。这仅对最后一项“categoryId”进行过滤,所有其他项:“is_active”、“gender”和“brand”都被忽略。为什么?因为它们在同一个对象下,而 JSON.. 以及我所知道的所有其他语言只能有一个键,而您在“bool”下有 4 次“必须”。
  • must 是一个条件数组,您将每个实例作为一个对象传递。
  • @Dalibor Karlović:非常感谢您的评论,我编辑了答案
  • 这不是过滤器,应该会影响排名,
猜你喜欢
  • 1970-01-01
  • 2019-06-28
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
相关资源
最近更新 更多