如何在elasticsearch中编写复杂的搜索查询

时间:2017-03-11 12:50:15

标签: php elasticsearch where

我正在使用laravel和elasticsearch 现在我想写一个搜索查询: 但我的问题是我不知道如何编写这样的查询: (preference_1 = Apples或preference_2 = Bananas)AND(preference_1 = Apples OR preference_2 = Cherries)AND preference_1 = Grapefruits

我知道如何写:(preference_1 =苹果和偏好_2 =香蕉)或(preference_1 =苹果和偏好_2 =樱桃)或偏好_1 =葡萄柚

有一个应该和多个必须它可能发生..但我不知道如何做反过来?

"query" => [
"bool" => [
            "should" => [[
                "bool" => [
                    "must" => [[
                        "match" => [
                            "preference_1" => "Apples"
                        ]
                    ], [
                        "match" => [
                            "preference_2" => "Bananas"
                        ]
                    ]]
                ]
            ], [
                "bool" => [
                    "must" => [[
                        "match" => [
                            "preference_1" => "Apples"
                        ]
                    ], [
                        "match" => [
                            "preference_2" => "Cherries"
                        ]
                    ]]
                ]
            ], [
                "match" => [
                    "preference_1" => "Grapefruit"
                ]
            ]]
        ]
]

我想知道如何写这个: (preference_1 =苹果或者偏好_2 =香蕉)和(preference_1 =苹果或者偏好_2 =樱桃)和preference_1 =葡萄柚

我读过elasticsearch doc,但我没有找到任何东西,或者一些例子..

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用filter and(非评分过滤器查询),方法与should相同。

{:query=>
  {:bool=>
    {:must=>[{:match_all=>{}}],
     :filter=>
      [{:bool=>
         {:should=>
           [{:term=>{:preference_1=>"Apples"}},
            {:term=>{:preference_2=>"Bananas"}}],
          :minimum_should_match=>1}},
       {:bool=>
         {:should=>
           [{:term=>{:preference_1=>"Apples"}},
            {:term=>{:preference_2=>"Cherries"}}],
          :minimum_should_match=>1}},
       {:bool=>
         {:should=>[{:term=>{:preference_1=>"Grapefruits"}}],
          :minimum_should_match=>1}}]}}}

答案 1 :(得分:0)

我的查询就像你的...但我删除了'必须',以使其工作

body => [
  query => [
     bool => [
        filter => [
        [
           bool => [
               should => [
                   [term => [preference_1 => "Apples" ]],
                   [term => [preference_2 =>"Bananas"  ]]
                ]
            ]
        ],
        [
           bool => [
              should => [
                [term => [preference_1 => "Apples" ]],
                [term => [preference_2=>"Cherries"]]
              ]
            ]
        ],
        [
           bool => [
              should => [
                [term => [preference_1 => "Grapefruits"]]
              ]
           ]
        ]
      ]
    ]
  ]
],
filter => [
 [
  term => [field3 => "dog" ]
 ]
]

但 当我主动过滤查询...弹性忽略我的身体查询。