Search code examples
elasticsearchfoselasticabundle

how to mast match all args pass in array in elastic search?


Here term gives result if one of all args (1,2) match and i need all args must have in degree.id of user
here i have data like this

"id": 66,
"name": null,
"degrees": [
    {
        "id": 1,
        "name": "BCA",
    },{
        "id": 2,
        "name": "MCA",
    }
]

So i need that, if BCA and MCA both degree exists only those record will be arrive in result

$term = new \Elastica\Query\Terms();
$term->setTerms('degrees.id', array('1','2'));

return $boolQuery->addMust($term);

Solution

  • What you're making with your setTerms is actually an OR on degrees field.

    To make an AND query, I recommend to use the Elastica\Query\BoolQuery class as follow :

    $BCAQuery = new Elastica\Query\Term();
    $BCAQuery->setTerm('degree.id', 1);
    
    $MCAQuery = new Elastica\Query\Term();
    $MCAQuery->setTerm('degree.id', 2);
    
    $boolQuery = new BoolQuery();
    $boolQuery->addMust($BCAQuery);
    $boolQuery->addMust($MCAQuery);
    

    Remember that if degrees is mapped as nested to use you bool query with Elastica\Query\Nested

    $degreesQuery = new Elastica\Query\Nested();
    $degreeQuery->setPath('degrees');
    $degreesQuery->setQuery($boolQuery);