Describes the practice of Elastic Search engine in SpringBoot.

Source: Internet
Author: User
Tags elastic search

Describes the practice of Elastic Search engine in SpringBoot.

Lab Environment

  1. ES version: 5.3.0
  2. Spring bt version: 1.5.9

First of all, we need to install the elastic search environment. We 'd better install the visualization plug-in elasticsearch-head to make it easy for us to view data intuitively.

Of course, this part can be referred to my post: Installation of elastic search on centos7

My ES is installed at http: // 113.209.119.170: 9200/. (This address must be configured in the springboot project)

Create a Spring Project

There is no special explanation for this part, but pay attention to it

When creating a project, remember to check the Elasticsearch dependency in web and NoSQL. Let's take a look at the following figure:

Select es dependency in Nosql when creating a project

After the project is automatically generated, the dependency of spring-boot-starter-data-elasticsearch is automatically added to pom. xml:

    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>    </dependency>

In this project, we use the open-source es java client jest Based on restful, so we also need to add the jest dependency in pom. xml:

    <dependency>      <groupId>io.searchbox</groupId>      <artifactId>jest</artifactId>    </dependency>

In addition, you must add jna dependencies:

    <dependency>      <groupId>net.java.dev.jna</groupId>      <artifactId>jna</artifactId>    </dependency>

Otherwise, the JNA not found. native methods will be disabled. error will be reported when the spring project is started:

JNA not found. native methods will be disabled.

In the project configuration file application. yml, You need to configure the es server address pair

Server: port: 6325 spring: elasticsearch: jest: uris:-http: // 113.209.119.170: 9200 # elasticsearch server address! Read-timeout: 5000

Code Organization

My project code is organized as follows:

Project Code Organization

A detailed explanation of each part of the code is as follows:

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; @ Servicepublic 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.exe cute (index); LOGGER.info ("ES inserted");} catch (IOException e) {e. printStackTrace (); LOGGER. error (e. getMessage () ;}}/*** save content in batches to 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.exe cute (bulk. build (); LOGGER.info ("ES inserted");} catch (IOException e) {e. printStackTrace (); LOGGER. error (e. getMessage () ;}}/*** search for content in 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.exe cute (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 interface"); 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 ;}}

Lab

You can use the postman tool to add several pieces of data, or enter the data directly in the browser. For example, add the following five pieces of data:

Http: // localhost: 6325/entityController/save? Id = 1 & name = http: // localhost: 6325/entityController/save? Id = 2 & name = China Nanjing Normal University http: // localhost: 6325/entityController/save? Id = 3 & name = Nanjing Confucius Temple http: // localhost: 6325/entityController/save? Id = 4 & name = Hangzhou is also very good http: // localhost: 6325/entityController/save? Id = 5 & name = South China, it seems that there are no cities with Beijing characters

The data insertion effect is as follows (use the visualization plug-in elasticsearch-head for viewing ):

Data insertion Effect

Let's test the search: for example, I want to search for the keyword "Nanjing"

In the browser, enter:

Http: // localhost: 6325/entityController/search? Name = Nanjing

The search result is as follows:

Search Result of the keyword "Nanjing"

All the four records that contain the keyword "Nanjing" have been searched out!

Of course, the standard word segmentation method is used here. Every Chinese text is used as a term, and all records containing the "South" and "Beijing" keywords are searched, the score is different. Of course, there are some other word segmentation methods. At this time, we need the support of other word segmentation plug-ins. This is not covered here, and we will explore it later.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.