Pregunta

I'm trying to get search results sorted, but I just get the unsorted results with the following code (in this example I query for all results):

$query = new \Elastica\Query();
$query->setSort(array('id' => array('order' => 'desc')));
$resultSet = $type->search($query); // where $type is an elastica type object
$results = $resultSet->getResults();

For reference, I'm using the FOSElasticaBundle with a Symfony2 project (using $type = $this->container->get('fos_elastica.index.website.myType');), but that should not make a difference.

If I make the query directly on the browser with http://localhost:9200/website/myType/_search?sort=id:desc&pretty=true, I get the results correctly sorted.

¿Fue útil?

Solución

Actually, the code given in the question is correct, and it does return the correctly sorted results.

The problem I was having was unrelated to Elastica and the code given in the question.

Turns out that the results I was retuning in my HTML were unsorted because I was not returning my Elastica Query results but the corresponding objects from my SQL database that were obtained from a query like this:

SELECT * FROM ...
WHERE id IN([ids from Elastica results in order])

The above SQL query does not return results in the order of the ids given in the "IN" clause, so it was necessary to re-order the SQL results to match the order of my ElasticSearch results (which I did with foreach statements). If I had been using MySQL I could have used ORDER BY FIELD(id, \[ids in order\]) to get SQL results in the same order as the ids provided in the IN clause.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top