Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get distances from lucene geo(spatial) search with version 4.0.0?

I'm trying geo search function with the latest version of Lucene(4.0.0), the requirement is simple: getting the points inside a circle(the center and radius are passed in as query condition). I can not find the API that outputs the distance of each result to center, I have to calculate the distance after I get out the latitude and longitude of each result. anyone can help? the code is listed below:

SpatialContext sc = SpatialContext.GEO;
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,
              sc.makeCircle(lo, la, DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
Filter geo_filter = strategy.makeFilter(args);
try {
    Sort chainedSort = new Sort(sfArray).rewrite(searcher);
    TopDocs docs = searcher.search(new MatchAllDocsQuery(), geo_filter, 10000, chainedSort);
    logger.debug("search finished, num: " + docs.totalHits);
    for (ScoreDoc scoreDoc : docs.scoreDocs){
        Document doc = searcher.doc(scoreDoc.doc);
        double la1 = Double.parseDouble(doc.get("la"));
        double lo1 = Double.parseDouble(doc.get("lo"));
        double distance = getDistance(la1, lo1, la, lo); // have to calc distance by myself here, not cool
    }
} catch (IOException e) {
    logger.error("fail to get the search result!", e);
}

It's easy to get distance with Lucene 3.X, anyone familiar with geo(spatial) search with Lucene 4.0.0?

like image 877
Jet Yang Avatar asked Nov 05 '12 04:11

Jet Yang


1 Answers

You have the lat & lon from the field; now you need to calculate the distance from the center point of the query circle. In your code, this would look like:

double distDEG = sc.getDistCalc().distance(args.getShape().getCenter(), lo1, la1);
double distKM = DistanceUtils.degrees2Dist(distDEG, DistanceUtils.EARTH_MEAN_RADIUS_KM);

Not bad; ehh? (p.s. I wrote much of Lucene 4 spatial)

like image 76
David Smiley Avatar answered Sep 22 '22 17:09

David Smiley