Search code examples
phpelasticsearchquerydsl

ElasticSearch match query multiple terms PHP


I am trying to construct must query on multiple terms, the array looks like this:

$params = [
'body' => [
    'query' => [
        "bool" => [
            "must" => [
                "terms" => [
                    "categories" => [
                        "Seating",
                    ],
                ],
                "terms" => [
                    "attributes.Color" => [
                        "Black",
                    ],
                ]
            ],
            "filter" => [
                "range" => [
                    "price" => [
                        "gte" => 39,
                        "lte" => 2999,
                    ],
                ],
            ],
        ],
    ],
    'from' => 0,
    'size' => 3,
],
];

Which is represented in JSON like this:

{
"query": {
    "bool": {
        "must": {
            "terms": {
                "attributes.Color": ["Black"]
            }
        },
        "filter": {
            "range": {
                "price": {
                    "gte": "39",
                    "lte": "2999"
                }
            }
        }
    }
},
"from": 0,
"size": 3
}

The problem is, JSON objects are represented as arrays in PHP so if I setup key for one array, it is rewritten. Do you have any idea on how to create multiple terms query in PHP?

Thanks in advance.


Solution

  • You need to add an additional array to enclose all your terms queries

    $params = [
    'body' => [
        'query' => [
            "bool" => [
                "must" => [
                  [
                    "terms" => [
                        "categories" => [
                            "Seating",
                        ],
                    ]
                  ],
                  [
                    "terms" => [
                        "attributes.Color" => [
                            "Black",
                        ],
                    ]
                  ]
                ],
                "filter" => [
                    "range" => [
                        "price" => [
                            "gte" => 39,
                            "lte" => 2999,
                        ],
                    ],
                ],
            ],
        ],
        'from' => 0,
        'size' => 3,
    ],
    ];