---
title: "使用Lucene-Spatial实现集成地理位置的全文检索"
author: "ssxxjjii"
date: "2013-08-09T09:11:49Z"
tags: []
categories: ["编程语言"]
slug: "lucene-spatial"
draft: false
lastmod: "2013-08-09T09:11:49Z"
id: 1922351
url: "https://tdcq.iteye.com/blog/1922351"
---

Lucene通过Spatial包提供了对基于地理位置的全文检索的支持，最典型的应用场景就是：“搜索中关村附近1公里内的火锅店，并按远近排序”。使用Lucene-Spatial添加对地理位置的支持，和之前普通文本搜索主要有两点区别：

        **1. 将坐标信息转化为笛卡尔层，建立索引**

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. private void indexLocation(Document document, JSONObject jo)
02. throws Exception {
03. double longitude = jo.getDouble("longitude");
04. double latitude = jo.getDouble("latitude");
05. document.add(new Field("lat", NumericUtils
06. .doubleToPrefixCoded(latitude), Field.Store.YES,
07. Field.Index.NOT\_ANALYZED));
08. document.add(new Field("lng", NumericUtils
09. .doubleToPrefixCoded(longitude), Field.Store.YES,
10. Field.Index.NOT\_ANALYZED));
11. for (int tier = startTier; tier &lt;= endTier; tier++) {
12. ctp = new CartesianTierPlotter(tier, projector,
13. CartesianTierPlotter.DEFALT\_FIELD\_PREFIX);
14. final double boxId = ctp.getTierBoxId(latitude, longitude);
15. document.add(new Field(ctp.getTierFieldName(), NumericUtils
16. .doubleToPrefixCoded(boxId), Field.Store.YES,
17. Field.Index.NOT\_ANALYZED\_NO\_NORMS));
18. }
19. }

        2. 搜索时，指定使用DistanceQueryFilter

 

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

1. DistanceQueryBuilder dq = new DistanceQueryBuilder(latitude,
2. longitude, miles, "lat", "lng",
3. CartesianTierPlotter.DEFALT\_FIELD\_PREFIX, true, startTier,
4. endTier);
5. DistanceFieldComparatorSource dsort = new DistanceFieldComparatorSource(
6. dq.getDistanceFilter());
7. Sort sort = new Sort(new SortField("geo\_distance", dsort));

      下面是基于Lucene3.2.0和JUnit4.8.2的完整代码。

 

 

**\[html]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. &lt;dependencies&gt;
02. &lt;dependency&gt;
03. &lt;groupId&gt;junit&lt;/groupId&gt;
04. &lt;artifactId&gt;junit&lt;/artifactId&gt;
05. &lt;version&gt;4.8.2&lt;/version&gt;
06. &lt;type&gt;jar&lt;/type&gt;
07. &lt;scope&gt;test&lt;/scope&gt;
08. &lt;/dependency&gt;
09. &lt;dependency&gt;
10. &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
11. &lt;artifactId&gt;lucene-core&lt;/artifactId&gt;
12. &lt;version&gt;3.2.0&lt;/version&gt;
13. &lt;type&gt;jar&lt;/type&gt;
14. &lt;scope&gt;compile&lt;/scope&gt;
15. &lt;/dependency&gt;
16. &lt;dependency&gt;
17. &lt;groupId&gt;org.apache.lucene&lt;/groupId&gt;
18. &lt;artifactId&gt;lucene-spatial&lt;/artifactId&gt;
19. &lt;version&gt;3.2.0&lt;/version&gt;
20. &lt;type&gt;jar&lt;/type&gt;
21. &lt;scope&gt;compile&lt;/scope&gt;
22. &lt;/dependency&gt;
23. &lt;dependency&gt;
24. &lt;groupId&gt;org.json&lt;/groupId&gt;
25. &lt;artifactId&gt;json&lt;/artifactId&gt;
26. &lt;version&gt;20100903&lt;/version&gt;
27. &lt;type&gt;jar&lt;/type&gt;
28. &lt;scope&gt;compile&lt;/scope&gt;
29. &lt;/dependency&gt;
30. &lt;/dependencies&gt;

 

 

        首先准备测试用的数据：

 

**\[plain]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. {"id":12,"title":"时尚码头美容美发热烫特价","longitude":116.3838183,"latitude":39.9629015}
02. {"id":17,"title":"审美个人美容美发套餐","longitude":116.386564,"latitude":39.966102}
03. {"id":23,"title":"海底捞吃300送300","longitude":116.38629,"latitude":39.9629573}
04. {"id":26,"title":"仅98元！享原价335元李老爹","longitude":116.3846175,"latitude":39.9629125}
05. {"id":29,"title":"都美造型烫染美发护理套餐","longitude":116.38629,"latitude":39.9629573}
06. {"id":30,"title":"仅售55元！原价80元的老舍茶馆相声下午场","longitude":116.0799914,"latitude":39.9655391}
07. {"id":33,"title":"仅售55元！原价80元的新笑声客栈早场","longitude":116.0799914,"latitude":39.9655391}
08. {"id":34,"title":"仅售39元（红色礼盒）！原价80元的平谷桃","longitude":116.0799914,"latitude":39.9655391}
09. {"id":46,"title":"仅售38元！原价180元地质礼堂白雪公主","longitude":116.0799914,"latitude":39.9655391}
10. {"id":49,"title":"仅99元！享原价342.7元自助餐","longitude":116.0799914,"latitude":39.9655391}
11. {"id":58,"title":"桑海教育暑期学生报名培训九折优惠券","longitude":116.0799914,"latitude":39.9655391}
12. {"id":59,"title":"全国发货：仅29元！贝玲妃超模粉红高光光","longitude":116.0799914,"latitude":39.9655391}
13. {"id":65,"title":"海之屿生态水族用品店抵用券","longitude":116.0799914,"latitude":39.9655391}
14. {"id":67,"title":"小区东门时尚烫染个人护理美发套餐","longitude":116.3799914,"latitude":39.9655391}
15. {"id":74,"title":"《郭德纲相声专辑》CD套装","longitude":116.0799914,"latitude":39.9655391}

     根据上面的测试数据，编写测试用例，分别搜索坐标（**116.3838183**, **39.9629015**）**3千米以内**的“**美发**”和全部内容，分别得到的结果应该是**4**条和**6**条。

 

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. import static org.junit.Assert.assertEquals;
02. import static org.junit.Assert.fail;
03. import java.util.List;
04. import org.junit.Test;
05. public class LuceneSpatialTest {
06. private static LuceneSpatial spatialSearcher = new LuceneSpatial();
07. @Test
08. public void testSearch() {
09. try {
10. long start = System.currentTimeMillis();
11. List&lt;String&gt; results = spatialSearcher.search("美发", 116.3838183, 39.9629015, 3.0);
12. System.out.println(results.size()
13. + "个匹配结果，共耗时 "
14. + (System.currentTimeMillis() - start) + "毫秒。\\n");
15. assertEquals(4, results.size());
16. } catch (Exception e) {
17. fail("Exception occurs...");
18. e.printStackTrace();
19. }
20. }
21. @Test
22. public void testSearchWithoutKeyword() {
23. try {
24. long start = System.currentTimeMillis();
25. List&lt;String&gt; results = spatialSearcher.search(null, 116.3838183, 39.9629015, 3.0);
26. System.out.println( results.size()
27. + "个匹配结果，共耗时 "
28. + (System.currentTimeMillis() - start) + "毫秒.\\n");
29. assertEquals(6, results.size());
30. } catch (Exception e) {
31. fail("Exception occurs...");
32. e.printStackTrace();
33. }
34. }
35. }

         下面是LuceneSpatial类，在构造函数中初始化变量和创建索引：

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. public class LuceneSpatial {
02. private Analyzer analyzer;
03. private IndexWriter writer;
04. private FSDirectory indexDirectory;
05. private IndexSearcher indexSearcher;
06. private IndexReader indexReader;
07. private String indexPath = "c:/lucene-spatial";
08. // Spatial
09. private IProjector projector;
10. private CartesianTierPlotter ctp;
11. public static final double RATE\_MILE\_TO\_KM = 1.609344; //英里和公里的比率
12. public static final String LAT\_FIELD = "lat";
13. public static final String LON\_FIELD = "lng";
14. private static final double MAX\_RANGE = 15.0; // 索引支持的最大范围，单位是千米
15. private static final double MIN\_RANGE = 3.0;  // 索引支持的最小范围，单位是千米
16. private int startTier;
17. private int endTier;
18. public LuceneSpatial() {
19. try {
20. init();
21. } catch (Exception e) {
22. e.printStackTrace();
23. }
24. }
25. private void init() throws Exception {
26. initializeSpatialOptions();
27. analyzer = new StandardAnalyzer(Version.LUCENE\_32);
28. File path = new File(indexPath);
29. boolean isNeedCreateIndex = false;
30. if (path.exists() && !path.isDirectory())
31. throw new Exception("Specified path is not a directory");
32. if (!path.exists()) {
33. path.mkdirs();
34. isNeedCreateIndex = true;
35. }
36. indexDirectory = FSDirectory.open(new File(indexPath));
37. //建立索引
38. if (isNeedCreateIndex) {
39. IndexWriterConfig indexWriterConfig = new IndexWriterConfig(
40. Version.LUCENE\_32, analyzer);
41. indexWriterConfig.setOpenMode(OpenMode.CREATE\_OR\_APPEND);
42. writer = new IndexWriter(indexDirectory, indexWriterConfig);
43. buildIndex();
44. }
45. indexReader = IndexReader.open(indexDirectory, true);
46. indexSearcher = new IndexSearcher(indexReader);
47. }
48. @SuppressWarnings("deprecation")
49. private void initializeSpatialOptions() {
50. projector = new SinusoidalProjector();
51. ctp = new CartesianTierPlotter(0, projector,
52. CartesianTierPlotter.DEFALT\_FIELD\_PREFIX);
53. startTier = ctp.bestFit(MAX\_RANGE / RATE\_MILE\_TO\_KM);
54. endTier = ctp.bestFit(MIN\_RANGE / RATE\_MILE\_TO\_KM);
55. }
56. private int mile2Meter(double miles) {
57. double dMeter = miles * RATE\_MILE\_TO\_KM * 1000;
58. return (int) dMeter;
59. }
60. private double km2Mile(double km) {
61. return km / RATE\_MILE\_TO\_KM;
62. }

 

 

              创建索引的具体实现：

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. private void buildIndex() {
02. BufferedReader br = null;
03. try {
04. //逐行添加测试数据到索引中，测试数据文件和源文件在同一个目录下
05. br = new BufferedReader(new InputStreamReader(
06. LuceneSpatial.class.getResourceAsStream("data")));
07. String line = null;
08. while ((line = br.readLine()) != null) {
09. index(new JSONObject(line));
10. }
11. writer.commit();
12. } catch (Exception e) {
13. e.printStackTrace();
14. } finally {
15. if (br != null) {
16. try {
17. br.close();
18. } catch (IOException e) {
19. e.printStackTrace();
20. }
21. }
22. }
23. }
24. private void index(JSONObject jo) throws Exception {
25. Document doc = new Document();
26. doc.add(new Field("id", jo.getString("id"), Field.Store.YES,
27. Field.Index.ANALYZED));
28. doc.add(new Field("title", jo.getString("title"), Field.Store.YES,
29. Field.Index.ANALYZED));
30. //将位置信息添加到索引中
31. indexLocation(doc, jo);
32. writer.addDocument(doc);
33. }
34. private void indexLocation(Document document, JSONObject jo)
35. throws Exception {
36. double longitude = jo.getDouble("longitude");
37. double latitude = jo.getDouble("latitude");
38. document.add(new Field("lat", NumericUtils
39. .doubleToPrefixCoded(latitude), Field.Store.YES,
40. Field.Index.NOT\_ANALYZED));
41. document.add(new Field("lng", NumericUtils
42. .doubleToPrefixCoded(longitude), Field.Store.YES,
43. Field.Index.NOT\_ANALYZED));
44. for (int tier = startTier; tier &lt;= endTier; tier++) {
45. ctp = new CartesianTierPlotter(tier, projector,
46. CartesianTierPlotter.DEFALT\_FIELD\_PREFIX);
47. final double boxId = ctp.getTierBoxId(latitude, longitude);
48. document.add(new Field(ctp.getTierFieldName(), NumericUtils
49. .doubleToPrefixCoded(boxId), Field.Store.YES,
50. Field.Index.NOT\_ANALYZED\_NO\_NORMS));
51. }
52. }

          搜索的具体实现：

 

 

**\[java]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. public List&lt;String&gt; search(String keyword, double longitude,
02. double latitude, double range) throws Exception {
03. List&lt;String&gt; result = new ArrayList&lt;String&gt;();
04. double miles = km2Mile(range);
05. DistanceQueryBuilder dq = new DistanceQueryBuilder(latitude,
06. longitude, miles, "lat", "lng",
07. CartesianTierPlotter.DEFALT\_FIELD\_PREFIX, true, startTier,
08. endTier);
09. //按照距离排序
10. DistanceFieldComparatorSource dsort = new DistanceFieldComparatorSource(
11. dq.getDistanceFilter());
12. Sort sort = new Sort(new SortField("geo\_distance", dsort));
13. Query query = buildQuery(keyword);
14. //搜索结果
15. TopDocs hits = indexSearcher.search(query, dq.getFilter(),
16. Integer.MAX\_VALUE, sort);
17. //获得各条结果相对应的距离
18. Map&lt;Integer, Double&gt; distances = dq.getDistanceFilter()
19. .getDistances();
20. for (int i = 0; i &lt; hits.totalHits; i++) {
21. final int docID = hits.scoreDocs\[i].doc;
22. final Document doc = indexSearcher.doc(docID);
23. final StringBuilder builder = new StringBuilder();
24. builder.append("找到了: ")
25. .append(doc.get("title"))
26. .append("， 距离: ")
27. .append(mile2Meter(distances.get(docID)))
28. .append("米。");
29. System.out.println(builder.toString());
30. result.add(builder.toString());
31. }
32. return result;
33. }
34. private Query buildQuery(String keyword) throws Exception {
35. //如果没有指定关键字，则返回范围内的所有结果
36. if (keyword == null || keyword.isEmpty()) {
37. return new MatchAllDocsQuery();
38. }
39. QueryParser parser = new QueryParser(Version.LUCENE\_32, "title",
40. analyzer);
41. parser.setDefaultOperator(Operator.AND);
42. return parser.parse(keyword.toString());
43. }

       

 

             执行测试用例，可以得到下面的结果：

 

**\[plain]** [view plain](http://blog.csdn.net/mydeman/article/details/6706553 "view plain")[copy](http://blog.csdn.net/mydeman/article/details/6706553 "copy")[print](http://blog.csdn.net/mydeman/article/details/6706553 "print")[?](http://blog.csdn.net/mydeman/article/details/6706553 "?")

01. 找到了: 时尚码头美容美发热烫特价， 距离: 0米。
02. 找到了: 都美造型烫染美发护理套餐， 距离: 210米。
03. 找到了: 审美个人美容美发套餐， 距离: 426米。
04. 找到了: 小区东门时尚烫染个人护理美发套餐， 距离: 439米。
05. 4个匹配结果，共耗时 119毫秒。
06. 找到了: 时尚码头美容美发热烫特价， 距离: 0米。
07. 找到了: 仅98元！享原价335元李老爹， 距离: 68米。
08. 找到了: 海底捞吃300送300， 距离: 210米。
09. 找到了: 都美造型烫染美发护理套餐， 距离: 210米。
10. 找到了: 审美个人美容美发套餐， 距离: 426米。
11. 找到了: 小区东门时尚烫染个人护理美发套餐， 距离: 439米。
12. 6个匹配结果，共耗时 3毫秒.

            参考文献：

 

            Lucene-Spatial的原理介绍：[http://www.nsshutdown.com/projects/lucene/whitepaper/locallucene.htm](http://www.nsshutdown.com/projects/lucene/whitepaper/locallucene.htm)

            GeoHash：[http://en.wikipedia.org/wiki/Geohash](http://en.wikipedia.org/wiki/Geohash)

            两篇示例（其中大部分代码就来自于这里）：

            [Spatial search with Lucene](http://www.mhaller.de/archives/156-Spatial-search-with-Lucene.html)  
            

# []()      [Lucene Spatial Example](http://develop.nydi.ch/2010/10/lucene-spatial-example/)

 

            

# []()     [使用 Apache Lucene 和 Solr 进行位置感知搜索](http://www.ibm.com/developerworks/cn/java/j-spatial/)