2

我正在尝试对搜索结果进行排序,但我只是使用以下代码获得未排序的结果(在此示例中,我查询所有结果):

$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();

作为参考,我将 FOSElasticaBundle 与 Symfony2 项目(使用$type = $this->container->get('fos_elastica.index.website.myType');)一起使用,但这不应该有所作为。

如果我使用 直接在浏览器上进行查询http://localhost:9200/website/myType/_search?sort=id:desc&pretty=true,我会得到正确排序的结果。

4

1 回答 1

2

实际上,问题中给出的代码是正确的,它确实返回了正确排序的结果。

我遇到的问题与 Elastica 和问题中给出的代码无关。

结果发现,我在 HTML 中重新调整的结果未排序,因为我没有返回 Elastica 查询结果,而是从我的 SQL 数据库中返回的相应对象,这些对象是从这样的查询中获得的:

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

上面的 SQL 查询没有按照“IN”子句中给出的 id 顺序返回结果,因此有必要重新排序 SQL 结果以匹配我的 ElasticSearch 结果的顺序(我使用 foreach 语句做了)。如果我一直在使用 MySQL,我可以使用ORDER BY FIELD(id, \[ids in order\])与 IN 子句中提供的 ID 相同的顺序来获取 SQL 结果。

于 2013-07-30T17:11:19.200 回答