構建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"}}