构建mapping
PUT /example { "mappings": { "doc": { "properties": { "location": { "type": "geo_shape" } } } } }初始化数据
POST /example/doc { "location" : { "type" : "polygon", "coordinates" : [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] } }
上例中大量的方括号可能看起来让人困惑,不过实际上 GeoJSON 的语法很是简单:html
用一个数组表示
经纬度
坐标点:java[lon,lat]
一组坐标点放到一个数组来表示一个多边形:数组
[[lon,lat],[lon,lat], ... ]
一个多边形(
polygon
)形状能够包含多个多边形;第一个表示多边形的外轮廓,后续的多边形表示第一个多边形内部的空洞:app[ [[lon,lat],[lon,lat], ... ], # main polygon [[lon,lat],[lon,lat], ... ], # hole in main polygon ... ]
参见 Geo-shape mapping documentation 了解更多支持的形状。elasticsearch
public class GeoLocationShopSearchApp { @SuppressWarnings({ "resource", "unchecked" }) public static void main(String[] args) throws Exception { Settings settings = Settings.builder() .put("cluster.name", "elasticsearch") .build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); ; Coordinate coordinate = new Coordinate(100.3, 0.3); GeoShapeQueryBuilder qb = null; try { qb = geoShapeQuery( "0", ShapeBuilders.newPoint(coordinate)); } catch (IOException e) { e.printStackTrace(); } qb.relation(ShapeRelation.INTERSECTS); SearchResponse response = client.prepareSearch("example") .setTypes("doc") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(qb) .setSize(200) .setFrom(0) .execute() .actionGet(); if (response != null && response.getHits() != null && response.getHits().getHits()!=null) { final ArrayList<SearchHit> searchHits = Lists.newArrayList(response.getHits().getHits()); searchHits.stream().forEach(searchHit -> printHitsSource(searchHit)); } client.close(); } public static void printHitsSource(SearchHit searchHitFields){ Map<String, Object> source = searchHitFields.getSource(); System.out.println(new Gson().toJson(source)); } }
{"location":{"coordinates":[[[100.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]],"type":"polygon"}}