0


I'm using elasticabundle for symfony2 and I want to sort results I'm seeking by distance I'm new to elasticsearch and I don't know how I can start the query I'm using :

$c = $this->container->get('fos_elastica.finder.cities_index.cities');
$nameQuery = new \Elastica\Query\Match();
$nameQuery->setFieldQuery('tokens', $city);
$nameQuery->setSort(array("distance" => "asc"));// I want to achieve this

Thanks for your time

Aysennoussi
  • 3,720
  • 3
  • 36
  • 60

1 Answers1

0

here is what I did following the example as provided by Dimitris Tsarouhas

The following setup allows to filter by keyword, order by id, and add all sort of other filtering using the $boolQuery ->addMust($yourfilter) formula.

We fetch the keyword as posted by a form. This is $data['query'] and by default we use it to perform a _all search, thus searching throughout all the fields listed in our config.yml file. To perform this search, we use the QueryString object, as this allows us to use wildcards.

We then look if exists the variable $data['status'], which comes through a dropdown select box (please note the use of strtolower(), without which the query wouldn't work - either that or you set up your own case-insensitive analyzer). If so, we use it to filter our results.

By default, we also want to narrow down our search and pick up only active users.

$data = $form->getData();
$finder = $this->container->get('fos_elastica.finder.search.user');

$keyword = $data['query'];
$status= $data['status'];

$keywordQuery = new QueryString;
$keywordQuery->setQuery('*' . $keyword . '*');

$query = new Query();
$query->setQuery($keywordQuery);
$query->setSort(array('id' => array('order' => 'asc')));

$boolQuery  = new Bool();

$active= new Term();
$active->setTerm('active', true);
$boolQuery ->addMust($active);

if (!empty($status)) {
    $statusQuery = new Term();
    $statusQuery->setTerm('status', strtolower($status->getName()));
    $boolQuery ->addMust($typeQuery);
}

$query->setFilter($boolQuery);

$entities = $finder->find($query);

And of course do not forget to import the necessary libraries:

use
    Elastica\Query\QueryString,
    Elastica\Query,
    Elastica\Filter\Bool,
    Elastica\Filter\Term
;

Remember that to be able to perform actions on fields (searching, sorting, etc) these haveto be included in your config.yml. Of course, this would cause the field to be automatically picked up when searching generally onto a certain entity. So, if you need to avoid this, but you still need certain fields to be available to elastica. just define it as showed below:

user:
    mappings:
        name: ~
        surname: ~
        status: ~
        active: { include_in_all: false }
        id: { include_in_all: false }
Community
  • 1
  • 1
cellulosa
  • 489
  • 1
  • 6
  • 18