当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Elastic Search搜索引擎在SpringBoot中的实践

详解Elastic Search搜索引擎在SpringBoot中的实践

2019年07月19日  | 移动技术网IT编程  | 我要评论

实验环境

  1. es版本:5.3.0
  2. spring bt版本:1.5.9

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

当然这部分可以参考本人的帖子:

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

spring工程创建

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

注意在新建项目时记得勾选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.的错误:

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

代码组织

我的项目代码组织如下:

项目代码组织

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

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条数据:

http://www.lhsxpumps.com/_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://www.lhsxpumps.com/_localhost:6325/entitycontroller/search?name=南京

搜索结果如下:

关键字“南京”的搜索结果

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网