Pergunta

I have some posts data and I use elasticsearch to search in title of these posts. Then I use filters to filter results based on category ids and some other parameters. What I'm trying to do is to get all categories of posts that matches the query criteria and ignore the filter.

Here is my what I have done so far. This is the query part:

if ( ! empty($search) )
{
    $query['multi_match'] = array(
        'query' => $search,
        'fields' => array('title', 'title_en')
    );
}

Then I apply some filters:

if ( ! empty($loc) )
{
    $filter['bool']['must'][]['geo_distance'] = array(
        'distance' => $distance . 'meters',
        'loc'      => $loc
    );
}

if ( isset($category) )
{
    $filter['bool']['must'][]['terms'] = array(
        'categories' => $category
    );
}

And then I facet part:

$facets = array(
    'categories' => array(
        'terms' => array(
            'field' => 'categories'
        )
    )
);

and the final part:

$searchParams['body']['query']['filtered'] = array(
    'query'  => $query,
    'filter' => $filter,
);
$searchParams['body']['facets'] = $facets;

The problem is that when I apply geo_distance or some other filters, this affects what is returned by the facet. I want the facet to be affected by the query only, so if the $search variable returns 100 results and then geo distance reduces that to 10, facet should return all categories from that 100 results, not 10. Is that possible using elasticsearch?

Foi útil?

Solução

You can achieve this by using top-level filter instead of "filtered" query. In your case it would probably look like this:

$searchParams['body']['query'] = $query;
$searchParams['body']['filter'] = $filter;
$searchParams['body']['facets'] = $facets;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top