Lucene空间:按距离排序

b5lpy0ml  于 2022-11-07  发布在  Lucene
关注(0)|答案(2)|浏览(310)

也许我在这里遗漏了一些东西,但是我不能让空间排序在Lucene Spatial(10.3)中工作,如SpatialExample.java中所述。

val searcher = placeSearcherManager.acquire()

val point = spatialCtx.makePoint(lat, lon)

val args =
  new SpatialArgs(SpatialOperation.Intersects,
    spatialCtx.makeCircle(lon, lat, 
    DistanceUtils.dist2Degrees(100, DistanceUtils.EARTH_MEAN_RADIUS_KM)))

val filter = spatialStrategy.makeFilter(args)

val valueSource = spatialStrategy.makeDistanceValueSource(point)

// Here's what's supposed to set up distance sorting
val distanceSort = new Sort(valueSource.getSortField(false)).rewrite(searcher)

try {  
  val topDocs = searcher.search(new MatchAllDocsQuery(), filter, limit, distanceSort) 
  val scoreDocs = topDocs.scoreDocs

  // Print the results
  scoreDocs.foreach(scoreDoc => {
    val doc = searcher.doc(scoreDoc.doc)
    val docPoint = spatialCtx.readShape(doc.get(spatialStrategy.getFieldName())).asInstanceOf[Point]
    val distance = spatialCtx.getDistCalc().distance(args.getShape.getCenter, docPoint)
    val distanceKM = DistanceUtils.degrees2Dist(distance, DistanceUtils.EARTH_EQUATORIAL_RADIUS_KM)
    Logger.info("distance: " + distanceKM)
  })
} finally {
  placeSearcherManager.release(searcher)
}

当我运行查询时,结果似乎根本不受排序的影响:

[info] application - distance: 406.01578203364323
[info] application - distance: 327.67269076509876
[info] application - distance: 218.94951150657565
[info] application - distance: 251.37927074183852
[info] application - distance: 140.6570939383426
[info] application - distance: 460.47502999630586
[info] application - distance: 462.37676932762116
[info] application - distance: 489.49001138999256
[info] application - distance: 392.0773262500455
[info] application - distance: 227.8864179949065

将排序顺序从升序更改为降序也没有效果。我看不出我所做的和官方示例有什么区别(除了使用SearcherManager,但我检查过了,这没有什么区别)。任何提示都很感谢!

9ceoxa92

9ceoxa921#

啊。回到回答我自己的问题。以防有人再偶然发现这个:在我的例子中,原因是我的代码使用了两个不同的策略对象来进行读和写--它们对GeoHashPrefixTree的maxLevel参数使用了不同的设置。- )

yzuktlbb

yzuktlbb2#

我是在lucene v6中实现,下面的代码可以从valueSource.getSortField(true)中的最近更改值开始排序,如果您想从valueSource.getSortField(true)中的最近更改值开始排序,

SpatialContext ctx = SpatialContext.GEO;
        String[] c = cord.split(",");
        double lat = Double.parseDouble(prms.getValue(c[0],true));
        double lng = Double.parseDouble(prms.getValue(c[1], true));
        Point currPt = ctx.makePoint(Double.valueOf(lng), Double.valueOf(lat));

        SpatialPrefixTree grid = new GeohashPrefixTree(ctx, 22);
        SpatialStrategy strategy = new RecursivePrefixTreeStrategy(grid, "location");
        ValueSource valueSource = strategy.makeDistanceValueSource(currPt);

        Sort distanceSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);
        TopDocs topDocs = searcher.search(baseQuery, Integer.MAX_VALUE,distanceSort);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

相关问题