Elastic Search搜索引擎在SpringBoot中的實踐

注: 本文首發於 My 公衆號 CodeSheep ,可 長按掃描 下面的 當心心 來訂閱 ↓ ↓ ↓java

CodeSheep · 程序羊


實驗環境

  • ES版本:5.3.0
  • spring bt版本:1.5.9

首先固然須要安裝好elastic search環境,最好再安裝上可視化插件 elasticsearch-head來便於咱們直觀地查看數據。web

固然這部分能夠參考本人的帖子: 《centos7上elastic search安裝填坑記》 https://www.jianshu.com/p/04f4d7b4a1d3spring

個人ES安裝在http://113.209.119.170:9200/這個地址(該地址須要配到springboot項目中去)sql


Spring工程建立

這部分沒有特殊要交代的,但有幾個注意點必定要小心apache

  • 注意在新建項目時記得勾選web和NoSQL中的Elasticsearch依賴,來張圖說明一下吧:

建立工程時勾選Nosql中的es依賴選項

項目自動生成之後pom.xml中會自動添加spring-boot-starter-data-elasticsearch的依賴:編程

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
複製代碼
  • 本項目中咱們使用開源的基於restful的es java客戶端jest,因此還須要在pom.xml中添加jest依賴:
<dependency>
			<groupId>io.searchbox</groupId>
			<artifactId>jest</artifactId>
		</dependency>
複製代碼
  • 除此以外還必須添加jna的依賴:
<dependency>
			<groupId>net.java.dev.jna</groupId>
			<artifactId>jna</artifactId>
		</dependency>
複製代碼

不然啓動spring項目的時候會報JNA not found. native methods will be disabled.的錯誤:c#

JNA not found. native methods will be disabled.

  • 項目的配置文件application.yml中須要把es服務器地址配置對
server:
  port: 6325

spring:
  elasticsearch:
    jest:
      uris:
      - http://113.209.119.170:9200  # ES服務器的地址!
      read-timeout: 5000
複製代碼

代碼組織

個人項目代碼組織以下: centos

項目代碼組織

各部分代碼詳解以下,註釋都有:瀏覽器

  • Entity.java
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;
    }


}

複製代碼
  • TestService.java
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);
}
複製代碼
  • TestServiceImpl.java
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;
    }
}

複製代碼
  • EntityController.java
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條數據:springboot

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,凡是包含「南」、「京」關鍵字的記錄都被搜索了出來,只是評分不一樣而已,固然還有其餘的一些分詞方式,此時須要其餘分詞插件的支持,此處暫不涉及,後文中再作探索。


後記

做者更多的SpringBt實踐文章在此:


若是有興趣,也能夠抽點時間看看做者一些關於容器化、微服務化方面的文章:


CodeSheep · 程序羊
相關文章
相關標籤/搜索