首先声明 我使用的ES版本是2.1,不同版本api可能不尽相同

1、首先创建索引mapping

(1)方法1

[java] view plaincopy
  1. // 创建索引方法1
  2. public static void createIndex2(String indexName, String indexType) throws IOException {
  3. Settings settings = Settings.settingsBuilder()
  4. .put("cluster.name", "cluster_wubing")
  5. .build();
  6. InetAddress inetAddress = InetAddress.getByName("192.168.1.107");;
  7. Client esClient = TransportClient.builder().settings(settings).build()
  8. .addTransportAddress(new InetSocketTransportAddress(inetAddress, 9300));
  9. //创建mapping,我这里使用的分词器analyzer/search_analyzer为ik,注意位置location类型为geo_point
  10. String mapping = "{\"properties\": {\n" +
  11. "      \"id\": {\n" +
  12. "        \"type\": \"integer\",\n" +
  13. "        \"index\": \"not_analyzed\",\n" +
  14. "        \"include_in_all\": false\n" +
  15. "      },\n" +
  16. "      \"title\": {\n" +
  17. "        \"type\": \"string\",\n" +
  18. "        \"store\": \"no\",\n" +
  19. "        \"term_vector\": \"with_positions_offsets\",\n" +
  20. "        \"analyzer\": \"ik_max_word\",\n" +
  21. "        \"search_analyzer\": \"ik_max_word\",\n" +
  22. "        \"include_in_all\": true\n" +
  23. "      },\n" +
  24. "      \"city\": {\n" +
  25. "        \"type\": \"string\",\n" +
  26. "        \"store\": \"no\",\n" +
  27. "        \"term_vector\": \"with_positions_offsets\",\n" +
  28. "        \"analyzer\": \"ik_max_word\",\n" +
  29. "        \"search_analyzer\": \"ik_max_word\",\n" +
  30. "        \"include_in_all\": true\n" +
  31. "      },\n" +
  32. "      \"location\":{\n" +
  33. "        \"type\":\"geo_point\",\n" +
  34. "        \"index\": \"not_analyzed\",\n" +
  35. "        \"include_in_all\": false\n" +
  36. "      }\n" +
  37. "    }}";
  38. esClient.admin().indices().prepareCreate(indexName).execute().actionGet();
  39. PutMappingResponse response  = esClient.admin().indices().preparePutMapping(indexName)
  40. .setType(indexType)
  41. .setSource(mapping)
  42. .get();
  43. if (!response.isAcknowledged()) {
  44. System.out.println("Could not define mapping for type [" + indexName + "]/[" + indexType + "].");
  45. } else {
  46. System.out.println("Mapping definition for [" + indexName + "]/[" + indexType + "] succesfully created.");
  47. }
  48. }

2.方法2此方法mapping易读。City类自己创建

[java] view plaincopy
  1. // 创建索引
  2. public static void createIndex(String indexName, String indexType) throws IOException {
  3. Settings settings = Settings.settingsBuilder()
  4. .put("cluster.name", "cluster_wubing")
  5. .build();
  6. InetAddress inetAddress = InetAddress.getByName("192.168.1.107");;
  7. Client esClient = TransportClient.builder().settings(settings).build()
  8. .addTransportAddress(new InetSocketTransportAddress(inetAddress, 9300));
  9. // 创建Mapping
  10. XContentBuilder mapping = createMapping(indexType);
  11. System.out.println("mapping:" + mapping.string());
  12. // 创建一个空索引
  13. esClient.admin().indices().prepareCreate(indexName).execute().actionGet();
  14. PutMappingRequest putMapping = Requests.putMappingRequest(indexName).type(indexType).source(mapping);
  15. PutMappingResponse response = esClient.admin().indices().putMapping(putMapping).actionGet();
  16. if (!response.isAcknowledged()) {
  17. System.out.println("Could not define mapping for type [" + indexName + "]/[" + indexType + "].");
  18. } else {
  19. System.out.println("Mapping definition for [" + indexName + "]/[" + indexType + "] succesfully created.");
  20. }
  21. }
  22. // 创建mapping
  23. public static XContentBuilder createMapping(String indexType) {
  24. XContentBuilder mapping = null;
  25. try {
  26. mapping = jsonBuilder().startObject()
  27. // 索引库名(类似数据库中的表)
  28. .startObject(indexType).startObject("properties")
  29. // ID
  30. .startObject("id").field("type", "long").endObject()
  31. // 城市
  32. .startObject("city").field("type", "string").endObject()
  33. // 位置
  34. .startObject("location").field("type", "geo_point").endObject()
  35. // 标题
  36. .startObject("title").field("type", "string").endObject()
  37. .endObject().endObject().endObject();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. return mapping;
  42. }

2、向索引里添加数据

[java] view plaincopy
  1. // 添加数据
  2. public static Integer addIndexData(String indexName, String indexType) throws Exception {
  3. Client client = ElasticSerachUtil.getClient();
  4. List<String> cityList = new ArrayList<String>();
  5. City city1 = new City(1L, "北京", 116.395645, 39.929986, "中国人民站起来了,北京人民可以天天站在天安门广场吃烤鸭了");
  6. City city2 = new City(2L, "天津", 117.210813, 39.143931, "中国人民站起来了,天津人民可以天天在迎宾广场吃麻花了");
  7. City city3 = new City(3L, "青岛", 120.384428, 36.105215, "中国人民站起来了,青岛人民可以天天在!最后一次,不要错过今天");
  8. City city4 = new City(4L, "哈尔滨", 126.657717, 45.773225, "中国人民站起来了,哈尔滨人民可以天天站在索菲亚广场吃红肠了");
  9. City city5 = new City(5L, "乌鲁木齐", 87.564988, 43.840381, "中国人民站起来了,乌鲁木齐人民可以天天在人民广场啃羊腿了");
  10. City city6 = new City(6L, "三亚", 109.522771, 18.257776, "中国人民站起来了,三亚人民可以让青岛政府去丢吧,让他们创城去吧!");
  11. cityList.add(obj2JsonUserData(city1));
  12. cityList.add(obj2JsonUserData(city2));
  13. cityList.add(obj2JsonUserData(city3));
  14. cityList.add(obj2JsonUserData(city4));
  15. cityList.add(obj2JsonUserData(city5));
  16. cityList.add(obj2JsonUserData(city6));
  17. // 创建索引库
  18. List<IndexRequest> requests = new ArrayList<IndexRequest>();
  19. for (int i = 0; i < cityList.size(); i++) {
  20. IndexRequest request = client.prepareIndex(indexName, indexType).setSource(cityList.get(i)).request();
  21. requests.add(request);
  22. }
  23. // 批量创建索引
  24. BulkRequestBuilder bulkRequest = client.prepareBulk();
  25. for (IndexRequest request : requests) {
  26. bulkRequest.add(request);
  27. }
  28. BulkResponse bulkResponse = bulkRequest.execute().actionGet();
  29. if (bulkResponse.hasFailures()) {
  30. System.out.println("批量创建索引错误!");
  31. }
  32. return bulkRequest.numberOfActions();
  33. }
  34. public static String obj2JsonUserData(City city) {
  35. String jsonData = null;
  36. try {
  37. // 使用XContentBuilder创建json数据
  38. XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
  39. jsonBuild.startObject().field("id", city.getId())
  40. .field("city", city.getCity())
  41. //注意纬度在前,经度在后 location类型
  42. .startArray("location").value(city.getLat()).value(city.getLon()).endArray()
  43. .field("title", city.getTitle())
  44. .endObject();
  45. jsonData = jsonBuild.string();
  46. System.out.println(jsonData);
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. return jsonData;
  51. }

3、最后创建search搜索和距离计算

[java] view plaincopy
  1. // 模糊查询
  2. public static void query(String query) throws Exception {
  3. Client client = ElasticSerachUtil.getClient();
  4. QueryStringQueryBuilder qsqb = new QueryStringQueryBuilder(query);
  5. // qsqb.analyzer("ik").field("title");
  6. qsqb.field("title");
  7. client.admin().indices().prepareRefresh().execute().actionGet();
  8. SearchResponse searchResponse = client.prepareSearch("testes").setTypes("xq").setQuery(qsqb)
  9. // .setScroll(new TimeValue(60000))
  10. .addFields("id", "title", "updatetime")
  11. // .addSort("updatetime", SortOrder.DESC)
  12. .addSort("_score", SortOrder.DESC)
  13. // .addHighlightedField("title")
  14. .setHighlighterEncoder("UTF-8").execute().actionGet();
  15. // 搜索耗时
  16. Float usetime = searchResponse.getTookInMillis() / 1000f;
  17. // 命中记录数
  18. Long hits = searchResponse.getHits().totalHits();
  19. System.out.println("查询到记录数=" + hits);
  20. for (SearchHit hit : searchResponse.getHits()) {
  21. // 打分
  22. Float score = hit.getScore();
  23. Integer id = Integer.parseInt(hit.getFields().get("id").value().toString());
  24. String title = hit.getFields().get("title").value().toString();
  25. System.out.println(title);
  26. }
  27. }
  28. // 获取附近的城市
  29. public static void testGetNearbyCities(Client client, String index, String type, double lat, double lon) throws ExecutionException, InterruptedException {
  30. SearchRequestBuilder srb = client.prepareSearch(index).setTypes(type);
  31. // srb.setPos
  32. // wx4g0th9p0gk 为北京的geohash 范围为lt(小于) 1500km内的数据
  33. QueryBuilder builder = geoDistanceRangeQuery("location")
  34. .point(lat,lon)//注意纬度在前,经度在后
  35. .from("0km")
  36. .to("10000km")
  37. .includeLower(true)
  38. .includeUpper(false)
  39. .optimizeBbox("memory")
  40. .geoDistance(GeoDistance.ARC);
  41. srb.setQuery(builder);
  42. // 获取距离多少公里 这个才是获取点与点之间的距离的
  43. //GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort("location");
  44. GeoDistanceSortBuilder sort = new GeoDistanceSortBuilder("location");
  45. sort.unit(DistanceUnit.KILOMETERS);//距离单位公里
  46. sort.order(SortOrder.ASC);
  47. sort.point(lat,lon);//注意纬度在前,经度在后
  48. srb.addSort(sort);
  49. SearchResponse searchResponse = srb.execute().actionGet();
  50. SearchHits hits = searchResponse.getHits();
  51. SearchHit[] searchHists = hits.getHits();
  52. System.out.println("北京附近的城市(" + hits.getTotalHits() + "个):");
  53. for (SearchHit hit : searchHists) {
  54. String city = (String) hit.getSource().get("city");
  55. String title = (String) hit.getSource().get("title");
  56. // 获取距离值,并保留两位小数点
  57. BigDecimal geoDis = new BigDecimal((Double) hit.getSortValues()[0]);
  58. Map<String, Object> hitMap = hit.getSource();
  59. // 在创建MAPPING的时候,属性名的不可为geoDistance。
  60. hitMap.put("geoDistance", geoDis.setScale(2, BigDecimal.ROUND_HALF_DOWN));
  61. System.out.println(city + "距离北京" + hit.getSource().get("geoDistance") + DistanceUnit.KILOMETERS.toString() + "---" + title);
  62. }
  63. }

4、写main方法测试

[java] view plaincopy
  1. public static void main(String[] args) throws Exception {
  2. Settings settings = Settings.settingsBuilder()
  3. .put("cluster.name", "cluster_wubing")
  4. .build();
  5. InetAddress inetAddress = InetAddress.getByName("192.168.1.107");;
  6. Client client = TransportClient.builder().settings(settings).build()
  7. .addTransportAddress(new InetSocketTransportAddress(inetAddress, 9300));
  8. String index = "testes2";
  9. String type = "xq2";
  10. //createIndex2(index, type);
  11. //addIndexData(index, type);
  12. double lat = 39.929986;
  13. double lon = 116.395645;
  14. long start = System.currentTimeMillis();
  15. testGetNearbyCities(client, index, type, lat, lon);
  16. query("政府");
  17. long end = System.currentTimeMillis();
  18. System.out.println((end - start) + "毫秒");
  19. client.close();
  20. }

搜索结果

ElasticSearch2.1 基于空间位置geo_query距离计算相关推荐

  1. 基于GPS与经纬度距离计算

    基于GPS与经纬度距离计算 # -*- coding:utf-8 -*- # /usr/bin/pythonimport warnings warnings.filterwarnings(" ...

  2. c#语言+计算两个位置的距离,计算两个GPS坐标的距离 方法一 - C#语言

    场景:已知两个GPS点的经纬度坐标信息.计算两点的距离. 1. 距离/纬度关系 GPS: 22.514519,113.380301 GPS: 22.511962,113.380301 距离:284.6 ...

  3. 图形处理(七)基于热传播的测地距离计算-Siggraph 2013

    这里要跟大家分享的是2013年Siggraph上面的一篇paper,名为<Geodesics in Heat:A New Approach to Computing Distance Based ...

  4. 基于百度地图api实现计算目标点与自身位置的距离(js)

    这里写自定义目录标题 导入api 获取自身定位 获取目标点定位 通过经纬度计算距离的函数 导入api 下面展示一些 内联代码片. ```javascript<script type=" ...

  5. 微信外卖小程序 怎么计算与客户的距离_微信小程序结合腾讯位置服务实现用户商家距离计算...

    前言 小程序实操,距离计算总结. 思路 一共有两种方法,各有利弊: 1.利用小程序的wx.getLocation 方法得到用户的经纬度,然后用已知的商家的经纬进行计算; 2.利用腾讯地图位置服务cal ...

  6. 移动端H5 腾讯地图sdk 当前位置 地址你解析 距离计算

    <template><view class="content"><view><input class="uni-input&qu ...

  7. Java实现对某一时刻GPS中圆轨道卫星的空间位置计算

    在上两文中给出了Java编程实现对RINEX格式的观测值文件和广播星历文件的读取(读取观测值文件链接https://blog.csdn.net/qq_40449816/article/details/ ...

  8. c#语言+计算两个位置的距离,C#计算两个经纬度之间的距离

    最近在项目中有一个功能需要计算两个经纬度之间的距离,在网上找了很多,也试了很多,下面的计算方法得出的结果是精度是最高,希望对大家有所帮助. private const double EARTH_RAD ...

  9. 基于js利用经纬度进行两地的距离计算

    转自:http://www.storyday.com/html/y2009/2212_according-to-latitude-and-longitude-distance-calculation- ...

  10. html GPS坐标实现,JavaScript 实现GPS坐标点距离计算(两个经/纬度间的距离计算)...

    在LBS(基于位置服务)的一些应用中,有时我们会需要计算两个用户或两个坐标点之间的距离.要解决这类问题,就要了解空间几何的概念并结合数学中在三角函数公式计算两点之间的值.本文介绍基于经度/纬度的,两个 ...

最新文章

  1. 装饰器的定义、语法糖用法及示例代码
  2. 喜得千金,升级做爸爸喽
  3. [转载] 英语科技论文写作——Difference between APAMLA
  4. docker部署openvas
  5. CSS三栏布局的四种方法
  6. 轻量级的Ajax解决方案——DynAjax:直接在客户端调用C#类的方法
  7. HALCON示例程序classify_image_class_mlp.hdev如何使用MLP分类器分割RGB图像
  8. C++复习总结(涵盖所有C++基本考点)!
  9. CSS3 响应式布局实例
  10. 证券投资深度学习_安信证券:“深度学习”开启新一轮计算模式变革
  11. 苹果Mac轻量级网页代码编辑器:​​​​​​​​​​​​Espresso
  12. 使用 requests 进行身份认证
  13. 在hbase 激活kerberos 下opentsdb的使用
  14. golang json string remove field
  15. linux命令从哪里敲,Linux 笔记本基于“敲打”的命令
  16. 信创终端违规外联案例分析及防控措施
  17. 分享一个好看的个人主页源码
  18. Delayed Project
  19. 网易详述8个月全过程:员工申请仲裁要求支付61万赔偿
  20. linux dhcpv6有状态配置,翻译:IPv6地址自动配置:有状态和无状态的区别

热门文章

  1. 漫谈Java IO之 NIO那些事儿
  2. 利用 Commons-Fileupload 实现文件上传分析(转)
  3. 自己动手写CPU之第七阶段(2)——简单算术操作指令实现过程
  4. 爬虫框架Scrapy之Spider
  5. bzoj3224: Tyvj 1728 普通平衡树
  6. CPU内存管理和linux内存分页机制
  7. jQuery(非插件)制作商城放大镜效果
  8. cocos2d-Lua视频教程
  9. *SQL Server系统表的应用
  10. Jquery、简单的下拉列表、网页左部导航菜单