ElasticSearch地理位置查询与分组

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

一、 使用场景
根据用户当前所在的地理位置坐标,按商品关键字查询出附近店铺的相关商品,并按店铺位置远近将搜索结果排序。
二、 场景说明
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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kingapex1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值