How to sort by geodist() function in Spring Solr Data?

时间:2017-08-04 12:41:18

标签: solr spring-data spatial spatial-query solr6

Ciao, I'm unable to get the following solr query working with Spring Solr Data.

q=name:rsa&sfield=coordinates&pt=-8.506854,115.262478&sort=geodist()%20asc

The query works if I put it inside solr admin console, but it doesn't work with spring solr data. I didn't find examples about geodist sorting inside documentation so I created a CustomRepository with the following function:

public Page<StructureDocument> findStructuresByNameAndCoordinates(String value, Point point, Pageable page) {

StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("name:*").append(value).append("*");
queryBuilder.append("&sfield=coordinates");
queryBuilder.append("&pt=").append(point.getX()).append(",").append(point.getY());
queryBuilder.append("&sort=geodist() asc");

Query query = new SimpleQuery(new SimpleStringCriteria(queryBuilder.toString())).setPageRequest(page);  

But it doesn't work because of syntax error (seems that Solrj doesn't like this chars (). This is the error:

; nested exception is org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException: Error from server at http://localhost:8983/solr: org.apache.solr.search.SyntaxError: Cannot parse 'name:*francesco*&sfield=coordinates&pt=-8.506854,115.262478&sort=geodist() asc': Encountered " ")" ") "" at line 1, column 71.

How can I sort by geodist function with spring solr data??

Thank you very much.

1 个答案:

答案 0 :(得分:0)

我在这里找到了一个解决方案SOLR Spring Data geospatial query

@Override
public Page<StructureDocument> 
findStructuresByNameAndCoordinates(String value, Point point, Pageable 
page){
SimpleQuery query = new SimpleQuery().setPageRequest(page);
query.addProjectionOnField("*");
query.addProjectionOnField("score");

StringBuffer buf = new StringBuffer("");
buf.append("{!geofilt pt=");
buf.append(point.getX());
buf.append(",");
buf.append(point.getY());
buf.append(" sfield=coordinates d=");
buf.append(2000.0);
buf.append(" score=distance}");

query.addCriteria(new SimpleStringCriteria(buf.toString()));

FilterQuery searchTerm = new SimpleFilterQuery();
searchTerm.addCriteria(new Criteria("name").contains(value));
query.addFilterQuery(searchTerm);

query.addSort(new Sort(Sort.Direction.ASC, "score"));

此外,我添加了我的solr文档“score”属性,用于存储geodist函数计算的距离值。

@Score
private Double score;

此解决方案有效,但我知道有一种更好的方法,实际上对我来说不起作用,请参阅此链接。我会继续调查它。

How to return distance and score in spatial search using spring-data-solr