ElasticSearch 搜索引擎在 SpringBoot 中的实践

2018-03-09 09:11:20 +08:00
 hansonwang99


实验环境

首先当然需要安装好 elastic search 环境,最好再安装上可视化插件 elasticsearch-head 来便于我们直观地查看数据。

当然这部分可以参考本人的帖子: 《 centos7 上 elastic search 安装填坑记》 https://www.jianshu.com/p/04f4d7b4a1d3

我的 ES 安装在 http://113.209.119.170:9200/这个地址(该地址需要配到 springboot 项目中去)


Spring 工程创建

这部分没有特殊要交代的,但有几个注意点一定要当心

项目自动生成以后 pom.xml 中会自动添加spring-boot-starter-data-elasticsearch的依赖:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>io.searchbox</groupId>
			<artifactId>jest</artifactId>
		</dependency>
		<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
		</dependency>

否则启动 spring 项目的时候会报JNA not found. native methods will be disabled.的错误:

server:
  port: 6325

spring:
  elasticsearch:
    jest:
      uris:
      - http://113.209.119.170:9200  # ES 服务器的地址!
      read-timeout: 5000

代码组织

我的项目代码组织如下:

各部分代码详解如下,注释都有:

package com.hansonwang99.springboot_es_demo.entity;
import java.io.Serializable;
import org.springframework.data.elasticsearch.annotations.Document;

public class Entity implements Serializable{

    private static final long serialVersionUID = -763638353551774166L;

    public static final String INDEX_NAME = "index_entity";

    public static final String TYPE = "tstype";

    private Long id;

    private String name;

    public Entity() {
        super();
    }

    public Entity(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


}

package com.hansonwang99.springboot_es_demo.service;

import com.hansonwang99.springboot_es_demo.entity.Entity;

import java.util.List;

public interface TestService {

    void saveEntity(Entity entity);

    void saveEntity(List<Entity> entityList);

    List<Entity> searchEntity(String searchContent);
}

package com.hansonwang99.springboot_es_demo.service.impl;

import java.io.IOException;
import java.util.List;

import com.hansonwang99.springboot_es_demo.entity.Entity;
import com.hansonwang99.springboot_es_demo.service.TestService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;

@Service
public class TestServiceImpl implements TestService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestServiceImpl.class);

    @Autowired
    private JestClient jestClient;

    @Override
    public void saveEntity(Entity entity) {
        Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
        try {
            jestClient.execute(index);
            LOGGER.info("ES 插入完成");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
    }


    /**
     * 批量保存内容到 ES
     */
    @Override
    public void saveEntity(List<Entity> entityList) {
        Bulk.Builder bulk = new Bulk.Builder();
        for(Entity entity : entityList) {
            Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
            bulk.addAction(index);
        }
        try {
            jestClient.execute(bulk.build());
            LOGGER.info("ES 插入完成");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
    }

    /**
     * 在 ES 中搜索内容
     */
    @Override
    public List<Entity> searchEntity(String searchContent){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent));
        //searchSourceBuilder.field("name");
        searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
        Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();
        try {
            JestResult result = jestClient.execute(search);
            return result.getSourceAsObjectList(Entity.class);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}

package com.hansonwang99.springboot_es_demo.controller;

import java.util.ArrayList;
import java.util.List;

import com.hansonwang99.springboot_es_demo.entity.Entity;
import com.hansonwang99.springboot_es_demo.service.TestService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/entityController")
public class EntityController {


    @Autowired
    TestService cityESService;

    @RequestMapping(value="/save", method=RequestMethod.GET)
    public String save(long id, String name) {
        System.out.println("save 接口");
        if(id>0 && StringUtils.isNotEmpty(name)) {
            Entity newEntity = new Entity(id,name);
            List<Entity> addList = new ArrayList<Entity>();
            addList.add(newEntity);
            cityESService.saveEntity(addList);
            return "OK";
        }else {
            return "Bad input value";
        }
    }

    @RequestMapping(value="/search", method=RequestMethod.GET)
    public List<Entity> save(String name) {
        List<Entity> entityList = null;
        if(StringUtils.isNotEmpty(name)) {
            entityList = cityESService.searchEntity(name);
        }
        return entityList;
    }
}

实际实验

增加几条数据,可以使用 postman 工具,也可以直接在浏览器中输入,如增加以下 5 条数据:

http://localhost:6325/entityController/save?id=1&name=南京中山陵
http://localhost:6325/entityController/save?id=2&name=中国南京师范大学
http://localhost:6325/entityController/save?id=3&name=南京夫子庙
http://localhost:6325/entityController/save?id=4&name=杭州也非常不错
http://localhost:6325/entityController/save?id=5&name=中国南边好像没有叫带京字的城市了

数据插入效果如下(使用可视化插件 elasticsearch-head 观看):

我们来做一下搜索的测试:例如我要搜索关键字“南京” 我们在浏览器中输入:

http://localhost:6325/entityController/search?name=南京

搜索结果如下:

刚才插入的 5 条记录中包含关键字“南京”的四条记录均被搜索出来了!

当然这里用的是 standard 分词方式,将每个中文都作为了一个 term,凡是包含“南”、“京”关键字的记录都被搜索了出来,只是评分不同而已,当然还有其他的一些分词方式,此时需要其他分词插件的支持,此处暂不涉及,后文中再做探索。


后记

作者更多的原创文章在此


3357 次点击
所在节点    程序员
11 条回复
southsala
2018-03-09 09:43:28 +08:00
两年前我要是能看到这篇文章 我就会少走很多弯路
rensuperk
2018-03-09 09:46:47 +08:00
@southsala 两年前 springBoot 还不支持 ES,得自己配置
x7395759
2018-03-09 09:47:32 +08:00
@southsala 走弯路的意义在于下次你遇到类似问题可以不走弯路,如果你看了问题下次遇到类似问题还是会走弯路,所以要相信,技术路上所有的弯路都是有意义的,虽然大多数的意义是浪费时间。
southsala
2018-03-09 09:53:08 +08:00
@rensuperk 那会没用 springboot,用的 SSH

@x7395759 只是看到楼主的文章感慨一下,解决问题,会产生一种自信,积累多了,也就不怕什么面对什么挑战了
hansonwang99
2018-03-09 10:12:31 +08:00
看你们的讨论好深入!
javen73
2018-03-09 10:19:10 +08:00
不错,正打算弄 es,我运气太好了,嘻嘻
JRay
2018-03-09 10:26:38 +08:00
ES 的原理就相当于是另外一个数据库?每次插入数据的时候都直接往里面插?那本地数据库还需要同步记录吗?
hansonwang99
2018-03-09 10:33:59 +08:00
@javen73 如果喜欢请多多关注,最新实践文章一般在简 shu 上最先放出来
gaocc
2018-03-09 10:40:45 +08:00
话说有其他 es 可视化界面插件推荐吗?自己在 linux 上整达到 head 感觉用起来好 low,主要是刷新问题,还有界面美观……
huangzxx
2018-03-09 10:53:36 +08:00
@gaocc

kopf 或 kibana
TZ
2018-03-09 15:21:31 +08:00
收藏下,以后用的到

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/436375

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX