弹性搜索1.7.3嵌套过滤器:对象数组中的匹配项

时间:2015-12-10 12:36:32

标签: elasticsearch

我正在尝试在弹性搜索中查询以下文档:

"amenity": [
        "Free Wifi",
        "Free Breakfast",
        "Veg Only",
        "Swimming Pool",
        "Newspaper",
        "Bar",
        "Credit Card",
        "Pickup & Drop",
        "Gym",
        "Elevator",
        "Valet Parking"
      ],
      "dodont": [
        {
          "do_or_dont": "Do",
          "what": "Vegetarians"
        },
        {
          "do_or_dont": "Do",
          "what": "Family"
        },
        {
          "do_or_dont": "Dont",
          "what": "Loud Music"
        },
        {
          "do_or_dont": "Dont",
          "what": "Booze"
        }
      ]

这是我写的查询:

"filter": {
    "and": {
      "filters": [
        {
          "nested" : {
            "path" : "dodont",
            "filter" : {
              "bool" : {
                "must": [{"and" : [
                        {
                            "term" : {"dodont.do_or_dont" : "Do"}
                        },
                        {
                            "term" : {"dodont.what" : "Vegetarians"}
                        }
                    ]},
                    {"and" : [
                        {
                            "term" : {"dodont.do_or_dont" : "Do"}
                        },
                        {
                            "term" : {"dodont.what" : "Family"}
                        }
                    ]}]  
              }

            }
          }
        }
      ]
    }
  }

现在这个查询返回空结果,但是当我在上面的代码中将bool中的“must”更改为“should”时,它会返回上面的文档作为结果(只有1个文档与上面的过滤器相匹配) ),但理想情况下,“必须”条件应该返回上面的文档,我想传递多个对象为Do和donts,我只想要匹配所有这些的结果,但我无法这样做。我应该怎么做呢?

1 个答案:

答案 0 :(得分:1)

您需要在嵌套文档中拆分这两个条件,因为dodont嵌套数组的每个元素在概念上都是一个单独的文档:

{
  "filter": {
    "and": {
      "filters": [
        {
          "nested": {
            "path": "dodont",
            "filter": {
              "and": [
                {
                  "term": {
                    "dodont.do_or_dont": "Do"
                  }
                },
                {
                  "term": {
                    "dodont.what": "Vegetarians"
                  }
                }
              ]
            }
          }
        },
        {
          "nested": {
            "path": "dodont",
            "filter": {
              "and": [
                {
                  "term": {
                    "dodont.do_or_dont": "Do"
                  }
                },
                {
                  "term": {
                    "dodont.what": "Family"
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}