现在手机app满天飞,我想大家都用过这个功能:【搜索我附近的饭店或宾馆】之类的功能,类似这样的地理位置搜索功能非常适用,因为它需要利用到用户当前的地理位置数据,是以用户角度出发,找到符合用户自身需求的信息,应用返回的信息对于用户来说满意度会比较高,可见,地理位置空间搜索在提高用户体验方面有至关重要的作用。在lucene中,地理位置空间搜索是借助spatial模块来实现的。
要实现地理位置空间搜索,我们首先需要对地理位置数据创建索引,比较容易想到的就是把经度和纬度存入索引,可是这样做,有个弊端,因为地理位置数据(经纬度)是非常精细的,一般两个地点相差就0.0几,这样我们需要构建的索引体积会很大,这会显著减慢你的搜索速度。在精确度上采取折衷的方法通常是将纬度和经度封装到层中。您可以将每个层看作是地图的特定部分的缩放级别,比如位于美国中央上方的第 2 层几乎包含了整个北美,而第 19 层可能只是某户人家的后院。尤其是,每个层都将地图分成 2层 # 的箱子或网格。然后给每个箱子分配一个号码并添加到文档索引中。如果希望使用一个字段,那么可以使用 geohash编码方式将纬度/经度编码到一个 string 中。geohash 的好处是能够通过切去散列码末尾的字符来实现任意的精度。在许多情况下,相邻的位置通常有相同的前缀。
同样比较重要的,就是距离计算,给定两个坐标点需要你计算这两个点之间的距离,至于怎么计算,这取决于你对地球怎么进行建模,一般对于距离计算精度要求不是很精确的(误差在10-20米范围内能接受的话)
采用平面模型就够了。当然你也可以计算球面模型,这样计算精度更精确,但更耗cpu,意味着计算时间更长,需要自己去优化。
下面给出一个spatial使用示例代码:

package com.yida.framework.lucene5.spatial;
import org.apache.lucene.document.document;
import org.apache.lucene.document.field;
import org.apache.lucene.document.numericdocvaluesfield;
import org.apache.lucene.document.storedfield;
import org.apache.lucene.index.directoryreader;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.indexwriter;
import org.apache.lucene.index.indexwriterconfig;
import org.apache.lucene.queries.function.valuesource;
import org.apache.lucene.search.filter;
import org.apache.lucene.search.indexsearcher;
import org.apache.lucene.search.matchalldocsquery;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.sort;
import org.apache.lucene.search.sortfield;
import org.apache.lucene.search.topdocs;
import org.apache.lucene.spatial.spatialstrategy;
import org.apache.lucene.spatial.prefix.recursiveprefixtreestrategy;
import org.apache.lucene.spatial.prefix.tree.geohashprefixtree;
import org.apache.lucene.spatial.prefix.tree.spatialprefixtree;
import org.apache.lucene.spatial.query.spatialargs;
import org.apache.lucene.spatial.query.spatialoperation;
import org.apache.lucene.store.directory;
import org.apache.lucene.store.ramdirectory;
import org.wltea.analyzer.lucene.ikanalyzer;
import com.spatial4j.core.context.spatialcontext;
import com.spatial4j.core.distance.distanceutils;
import com.spatial4j.core.shape.point;
import com.spatial4j.core.shape.shape;
/**
* lucene地理位置查询测试
*
* @author lanxiaowei
*/
public class lucenespatialtest {
/** spatial上下文 */
private spatialcontext ctx;
/** 提供索引和查询模型的策略接口 */
private spatialstrategy strategy;
/** 索引目录 */
private directory directory;
/**
* spatial初始化
*/
protected void init() {
// spatialcontext也可以通过spatialcontextfactory工厂类来构建
this.ctx = spatialcontext.geo;
//网格最大11层
int maxlevels = 11;
// spatialprefixtree也可以通过spatialprefixtreefactory工厂类构建
spatialprefixtree grid = new geohashprefixtree(ctx, maxlevels);
this.strategy = new recursiveprefixtreestrategy(grid, "mygeofield");
// 初始化索引目录
this.directory = new ramdirectory();
}
private void indexpoints() throws exception {
indexwriterconfig iwconfig = new indexwriterconfig(new ikanalyzer());
indexwriter indexwriter = new indexwriter(directory, iwconfig);
//这里的x,y即经纬度,x为longitude(经度),y为latitude(纬度)
indexwriter.adddocument(newsampledocument(2,
ctx.makepoint(-80.93, 33.77)));
/** wkt表示法:point(longitude,latitude)*/
indexwriter.adddocument(newsampledocument(4,
ctx.readshapefromwkt("point(60.9289094 -50.7693246)")));
indexwriter.adddocument(newsampledocument(20, ctx.makepoint(0.1, 0.1),
ctx.makepoint(0, 0)));
indexwriter.close();
* 创建document索引对象
*
* @param id
* @param shapes
* @return
private document newsampledocument(int id, shape... shapes) {
document doc = new document();
doc.add(new storedfield("id", id));
doc.add(new numericdocvaluesfield("id", id));
for (shape shape : shapes) {
for (field f : strategy.createindexablefields(shape)) {
doc.add(f);
}
point pt = (point) shape;
doc.add(new storedfield(strategy.getfieldname(), pt.getx() + " "
+ pt.gety()));
}
return doc;
* 地理位置搜索
* @throws exception
private void search() throws exception {
indexreader indexreader = directoryreader.open(directory);
indexsearcher indexsearcher = new indexsearcher(indexreader);
// 按照id升序排序
sort idsort = new sort(new sortfield("id", sortfield.type.int));
//搜索方圆200千米范围以内,这里-80.0, 33.0分别是当前位置的经纬度,以当前位置为圆心,200千米为半径画圆
//注意后面的earth_mean_radius_km表示200的单位是千米,看到km了么。
spatialargs args = new spatialargs(spatialoperation.intersects,
ctx.makecircle(-80.0, 33.0, distanceutils.dist2degrees(200,
distanceutils.earth_mean_radius_km)));
//根据spatialargs参数创建过滤器
filter filter = strategy.makefilter(args);
//开始搜索
topdocs docs = indexsearcher.search(new matchalldocsquery(), filter,
10, idsort);
document doc1 = indexsearcher.doc(docs.scoredocs[0].doc);
string doc1str = doc1.getfield(strategy.getfieldname()).stringvalue();
int spaceidx = doc1str.indexof(' ');
double x = double.parsedouble(doc1str.substring(0, spaceidx));
double y = double.parsedouble(doc1str.substring(spaceidx + 1));
double doc1distdeg = ctx
.calcdistance(args.getshape().getcenter(), x, y);
system.out.println("(longitude,latitude):" + "(" + x + "," + y + ")");
system.out.println("doc1distdeg:" + doc1distdeg * distanceutils.deg_to_km);
system.out.println(distanceutils.degrees2dist(doc1distdeg,distanceutils.earth_mean_radius_km));
//定义一个坐标点(x,y)即(经度,纬度)即当前用户所在地点
point pt = ctx.makepoint(60, -50);
//计算当前用户所在坐标点与索引坐标点中心之间的距离即当前用户地点与每个待匹配地点之间的距离,deg_to_km表示以km为单位
valuesource valuesource = strategy.makedistancevaluesource(pt,
distanceutils.deg_to_km);
//根据命中点与当前位置坐标点的距离远近降序排,距离数字大的排在前面,false表示降序,true表示升序
sort distsort = new sort(valuesource.getsortfield(false))
.rewrite(indexsearcher);
topdocs topdocs = indexsearcher.search(new matchalldocsquery(), 10,
distsort);
scoredoc[] scoredocs = topdocs.scoredocs;
for (scoredoc scoredoc : scoredocs) {
int docid = scoredoc.doc;
document document = indexsearcher.doc(docid);
int gotid = document.getfield("id").numericvalue().intvalue();
string geofield = document.getfield(strategy.getfieldname()).stringvalue();
int xy = geofield.indexof(' ');
double xpoint = double.parsedouble(geofield.substring(0, xy));
double ypoint = double.parsedouble(geofield.substring(xy + 1));
double distdeg = ctx
.calcdistance(args.getshape().getcenter(), xpoint, ypoint);
double juli = distanceutils.degrees2dist(distdeg,distanceutils.earth_mean_radius_km);
system.out.println("docid:" + docid + ",id:" + gotid + ",distance:" + juli + "km");
/*args = new spatialargs(spatialoperation.intersects, ctx.makecircle(
-80.0, 33.0, 1));
spatialargs args2 = new spatialargsparser().parse(
"intersects(buffer(point(-80 33),1))", ctx);
system.out.println("args2:" + args2.tostring());*/
indexreader.close();
public static void main(string[] args) throws exception {
lucenespatialtest lucenespatialtest = new lucenespatialtest();
lucenespatialtest.init();
lucenespatialtest.indexpoints();
lucenespatialtest.search();
}
有关wtk 空间数据表示法参考资料:
wkt - 概念
wkt - 几何对象
wkt可以表示的几何对象包括:点,线,多边形,tin(不规则三角网)及多面体。可以通过几何集合的方式来表示不同维度的几何对象。
几何物体的坐标可以是2d(x,y),3d(x,y,z),4d(x,y,z,m),加上一个属于线性参照系统的m值。
以下为几何wkt字串样例:
point(6 10)
linestring(3 4,10 50,20 25)
polygon((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2))
multipoint(3.5 5.6, 4.8 10.5)
multilinestring((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))
multipolygon(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3)))
geometrycollection(point(4 6),linestring(4 6,7 10))
point zm (1 1 5 60)
point m (1 1 80)
point empty
multipolygon empty
wkt - 空间参照系统
一个表示空间参照系统的wkt字串描述了空间物体的测地基准、大地水准面、坐标系统及地图投影。
wkt在许多gis程序中被广泛采用。esri亦在其shape文件格式(*.prj)中使用wkt。
以下是空间参照系统的wkt表示样例:
compd_cs["osgb36 / british national grid + odn",
projcs["osgb 1936 / british national grid",
geogcs["osgb 1936",
datum["osgb_1936",
spheroid["airy 1830",6377563.396,299.3249646,authority["epsg","7001"]],
towgs84[375,-111,431,0,0,0,0],
authority["epsg","6277"]],
primem["greenwich",0,authority["epsg","8901"]],
unit["dmsh",0.0174532925199433,authority["epsg","9108"]],
axis["lat",north],
axis["long",east],
authority["epsg","4277"]],
projection["transverse_mercator"],
parameter["latitude_of_origin",49],
parameter["central_meridian",-2],
parameter["scale_factor",0.999601272],
parameter["false_easting",400000],
parameter["false_northing",-100000],
unit["metre",1,authority["epsg","9001"]],
axis["e",east],
axis["n",north],
authority["epsg","27700"]],
vert_cs["newlyn",
vert_datum["ordnance datum newlyn",2005,authority["epsg","5101"]],
axis["up",up],
authority["epsg","5701"]],
authority["epsg","7405"]]
关于如何对地球进行建模方面的知识,请自己google学习,比如平面建模,球面建模,曼哈顿距离等等,平面建模一般采用勾股定理或其变体就能解决,球面建模一般是采用求大圆弧长来解决,在lucene spatial中有haversine 和 geohash haversine两个公式实现。至于haversine公式的算法以及geoahash编码的算法啊自己google学习去吧。demo源码请看底下的附件!!!
如果你还有什么问题请加我Q-q:7-3-6-0-3-1-3-0-5,
或者加裙
一起交流学习!
转载:http://iamyida.iteye.com/blog/2204455