Working of filters with elastica

1.3k views Asked by At

How to apply filters in elastica library which works with elastic search.

Need an example of term filters.

$query1 = new \Elastica\Filter\Term();
$query1->setTerm('categories', array('short_description' =>'test metal'));
$bool->addShould($query);

or

$query1 = new \Elastica\Filter\Term();
$query1->setTerm('categories', 'test metal');

I am trying to use above ways which is resulting in following error

Invalid parameter. Has to be array or instance of Elastica\Query\AbstractQuery

2

There are 2 answers

1
czende On

Filters are deprecated. Use queries in filter context.

For example:

{
"query": { 
"bool": { 
  "must": [
    { "match": { "title":   "Search"        }}, 
    { "match": { "content": "Elasticsearch" }}  
  ],
  "filter": [ 
    { "term":  { "status": "published" }}, 
    { "range": { "publish_date": { "gte": "2015-01-01" }}} 
  ]
}
}
}

EDIT: @Sattu I'm using Elastica too. It depends which version of Elastica you have. If you have v3.2.3 you have to use raw query. Something like this:

$query = [
'query' => [
  'bool' => [
    'filter' => [
      'term => [$field => $value]
     ]
   ]
  ]
];
$index = $client->getIndex('products);
$type = $index->getType('product');
$type->search($query);

But if you have Elastica v5 you can use Elastica\Query class and set filter through addFilter() method.

0
Ales On

ruflin/elastica v 7.0.1:

$bool = new Elastica\Query\BoolQuery();
$filter = new Elastica\Query\Term(['tagType' => 'value']);
$bool->addFilter($filter);