Search code examples
elasticsearchelasticsearch-php

Multiple OR and AND conditions with Elasticsearch php


I would like to achieve the following query with ElasticSearch :

product_shipper = 1 AND ((product_type = product and price>0) OR (product_type = product_variation and price=0))

I've built the following query but it doesn't work, sending me an empty result :

              "query"=> [
                  "bool"=> [
                     "must"=> [
                        [
                           "bool"=> [
                              "should" => [
                                    "bool"=> [
                                        "must"=> [
                                            [ "match" => [ "product_type" => "product" ] ],
                                            [ 
                                                'range'=>['price'=>['gt'=>0]]
                                            ],
                                        ]
                                    ],
                                     "bool"=> [
                                        "must"=> [
                                            [ "match" => [ "product_type" => "product_variation" ] ],
                                            [ "match" => [ "price" => 0 ] ]
                                        ]
                                    ]
                              ]
                           ]
                        ],
                        [ 'match' => [ 'product_shipper' => $shipper ] ],
                     ]
                  ]
               ]

What am I doing wrong?


Solution

  • I had a tiny issue in my syntax at the should clause level, here is the working code example, hope it helps a lot of people starting with Elasticsearch.

    "query"=> [
    "bool"=> [
        "must"=> [
            [
                "bool"=> [
                    "should" => [
                        [
                            "bool"=> [
                                "must"=> [
                                    [ "match" => [ "product_type" => "product" ] ],
                                    [ "range"=>['price'=>['gt'=>0]]],
                                ]
                            ],
                        ],
                        [
                            "bool"=> [
                                "must"=> [
                                    [ "match" => [ "product_type" => "product_variation" ] ],
                                    ['range'=>['price'=>['lte'=>0]]]
                                ]
                            ]
                        ]
                    ]
                ]
            ],
            [
                'match' => [ 'product_shipper' => $shipper ]
            ],
        ]
    ]
    ]