一、 使用场景
根据用户当前所在的地理位置坐标,按商品关键字查询出附近店铺的相关商品,并按店铺位置远近将搜索结果排序。
二、 场景说明
1、 按商品关键字搜索,比如关键字为“牛奶”,那么需要搜索出附近店铺发布的带有“牛奶”关键字的商品。
2、 商品不会带有位置信息,但是商品所属的店铺是有位置信息的,因此要将店铺的位置信息存放进商品的ES索引中。
三、 具体实现
1、 ES索引和Mapping的创建
地理坐标点不能被动态映射(dynamic mapping)自动检测,而是需要显式声明对应字段类型为geo-point,如下:

创建索引和mapping具体代码如下(以下代码为单元测试类,可根据业务需要自定义修改):
public class CreateIndex {
/** 商品索引名称 */
private static final String INDEX_NAME = "goods_index";
/** ES cluster-name*/
private static final String CLUSTER_NAME = "es_cluster";
/** ES cluster-nodes*/
private static final String CLUSTER_NODES = "127.0.0.1:9300";
/** ES 用户密码*/
private static final String USER_PASSWORD = "";
@Test
public void create() {
EsTemplateBuilder esTemplateBuilder;
//如果用户验证
if(!StringUtil.isEmpty(USER_PASSWORD)){
esTemplateBuilder = new DefaultEsTemplateBuilder().setClusterName(CLUSTER_NAME).setClusterNodes(CLUSTER_NODES).setUserPass(USER_PASSWORD);
}else{
esTemplateBuilder = new DefaultEsTemplateBuilder().setClusterName(CLUSTER_NAME).setClusterNodes(CLUSTER_NODES);
}
ElasticsearchTemplate esTemplate = esTemplateBuilder.build();
//商品索引名称
String goodsIndexName = INDEX_NAME + "_" + EsSettings.GOODS_INDEX_NAME;
//先删除商品索引,再创建
esTemplate.deleteIndex(goodsIndexName);
esTemplate.createIndex(goodsIndexName);
//获取商品索引mapping
Map goodsMapping = createGoodsMapping();
//创建商品索引mapping
esTemplate.putMapping(goodsIndexName, EsSettings.GOODS_TYPE_NAME, goodsMapping);
}
/**
* 创建商品索引mapping
* @return
*/
private Map createGoodsMapping() {
Map goodsMap = new HashMap();
goodsMap.put("goodsId", new MyMap().put("type", "long").getMap());
goodsMap.put("goodsName", new MyMap().put("type", "text").put("analyzer", "ik_max_word").getMap());
goodsMap.put("sellerId", new MyMap().put("type", "integer").getMap());
goodsMap.put("location", new MyMap().put("type", "geo_point").getMap());
//其它字段略...
return new MyMap().put("properties", goodsMap).getMap()

本文介绍了一种基于地理位置坐标和商品关键字的搜索系统,该系统能够查找附近店铺的相关商品,并按店铺距离排序。详细阐述了如何在Elasticsearch中创建地理坐标索引、商品信息索引及搜索逻辑。
最低0.47元/天 解锁文章
616

被折叠的 条评论
为什么被折叠?



