Elasticsearch geographic location information maintenance and retrieval case sharing
1. Preparations
Refer to the document " Introduction to the use of high-performance elasticsearch ORM development library " to import and configure the es client to the project
2. Define mapping with geographic location type
Create a city index table structure, the field location type is geo_point, and define a retrieved dsl statement
Create a file esmapper/address.xml in the resources directory with the following contents:
<properties>
<property name="createCityIndice"><![CDATA[{
"settings": {
"number_of_shards": 6,
"index.refresh_interval": "5s"
},
"mappings": {
"city": {
"properties": {
"standardAddrId":{
"type":"keyword"
},
"detailName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"cityName":{
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"countyName":{
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"location":{
"type": "geo_point"
}
}
}
}
}]]></property>
<property name="locationSearch"><![CDATA[{
"size": 100,
"query": {
"bool": {
"must": [
{
"match_phrase_prefix" : {
"detailName" : {
"query" : #[detailName]
}
}
},
{
"geo_distance": {
"distance": #[distance],
"location": {
"lon": #[lon],
"lat": #[lat]
}
}
}
]
}
}
}]]></property>
</properties>
Create an index table
//创建加载配置文件的客户端工具,单实例多线程安全,第一次运行要预加载,有点慢
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/address.xml");
try {
//先删除mapping
clientUtil.dropIndice("city");
} catch (ElasticSearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//再创建mapping
clientUtil.createIndiceMapping("city",//索引表名称
"createCityIndice");//索引表mapping dsl脚本名称,在esmapper/address.xml中定义createCityIndice
3. Add index documents
Map<String,String> params = new HashMap<String,String>();
params.put("cityName","潭市");
params.put("standardAddrId","38130122");
params.put("detailName","贵溪市花园办事处建设路四冶生活区4-11栋33单元1层1010");
params.put("location","28.292781,117.238963");
params.put("countyName","中国");
ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
clientUtil.addDocument("city",//索引名称
"city",//索引类型
params);//索引数据对象
"refresh");//强制刷新索引数据,让插入数据实时生效,如果考虑性能需要,可以去掉refresh参数
4. Geographical location retrieval
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/address.xml");
Map<String,String> params = new HashMap<String,String>();
params.put("detailName","海域香廷160栋1单元3层302室");
params.put("distance","0.5km");
params.put("lon","115.824994");
params.put("lat","28.666162");
//返回map对象列表,也可以返回其他实体对象列表
ESDatas<Map> datas = clientUtil.searchList("city/_search","locationSearch",params,Map.class);
//返回json报文
System.out.print(clientUtil.executeRequest("city/_search","locationSearch",params));
5. Reference Documentation
For more bboss usage documentation, please refer to: