Search code examples
elasticsearchquerydsl

Elasticsearch AND condition with term query


This is my search filter query , I want to give "and" condition for terms. Now I have given must inside the filter condition

'query' => [
    "filtered" => [
        "query" => [
            "match_all" => []
        ],
        "filter" => [
            "bool" => [
                "must" => [
                    "terms" => [
                        "num" => [
                            1,2,3
                        ]
                    ],
                    "terms" => [
                        "sample" => [
                            "a", "b"
                        ],
                    ]
                ]
            ]
        ],
        'query' => [
            'multi_match' => [
                'query' => "Hello",
                'fields' => ['text'],
                'operator' => 'and'
            ],
        ]
    ]
],

but its not working. Any other solution for this?


Solution

  • You need to enclose your terms filters in one more array, otherwise your bool/must becomes an associative array and that's not what you want (i.e. one of the terms filter gets discarded).

    'query' => [
        "filtered" => [
            "query" => [
                "match_all" => []
            ],
            "filter" => [
                "bool" => [
                    "must" => [
                       [                     <---
                          "terms" => [
                             "num" => [
                                1,2,3
                             ]
                          ]
                       ],                    <---
                       [                     <---
                          "terms" => [
                            "sample" => [
                                "a", "b"
                            ],
                          ]
                       ]                     <---
                    ]
                ]
            ],
            'query' => [
                'multi_match' => [
                    'query' => "Hello",
                    'fields' => ['text'],
                    'operator' => 'and'
                ],
            ]
        ]
    ],