Experimental environment

  • ES version: 5.3.0
  • Spring BT version: 1.5.9

You’ll need to install Elastic Search, and you’ll need to install elasticSearch-Head to see your data visually.

Of course you can refer to my post on “Installing Elastic Search on Centos7” www.jianshu.com/p/04f…

My ES installed in http://113.209.119.170:9200/ address (the address needs to match to springboot project)


Spring Project Creation

There is nothing special to be said for this part, but there are a few things to be careful about

  • Select the web and NoSQL dependencies for Elasticsearch when creating a new project.

Pom after project is automatically generated. In the XML automatically add spring – the boot – starter – data – elasticsearch depends on:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId>  </dependency>Copy the code
  • In this project we use an open source RESTFUL ES Java clientjest, so you also need to add it in pom.xmljestRely on:
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
        </dependency>Copy the code
  • You have to add something elsejnaThe dependence of:
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
        </dependency>Copy the code

JNA not found. Native methods will be disabled. Error:

  • The es server address needs to be configured correctly in the project configuration file application.yml
Server: port: 6325 spring: elasticsearch: jest: uris, : - http://113.209.119.170:9200 # ES server address! read-timeout: 5000Copy the code

Code organization

My project code is organized as follows:

Detailed explanation of each part of the code is as follows, with annotations:

  • 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; }}Copy the code
  • 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);
}Copy the code
  • 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 inserted complete "); } catch (IOException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); 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 inserted complete "); } catch (IOException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); */ 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; }}Copy the code
  • 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; }}Copy the code

The actual experiment

To add some data, you can use the Postman tool or directly enter the data in the browser. For example, add the following five data:

http://localhost:6325/entityController/save?id=1&name= tomb http://localhost:6325/entityController/save?id=2&name= China nanjing normal university http://localhost:6325/entityController/save?id=3&name= nanjing Confucius temple Hangzhou is also very good at http://localhost:6325/entityController/save?id=4&name= http://localhost:6325/entityController/save?id=5&name= the words seem not call with Beijing south city in ChinaCopy the code

Insert data as follows (use the visualization plugin ElasticSearch-head to view it) :

Let’s test the search: for example, if I want to search for the keyword “Nanjing”, we type in the browser:

Nanjing http://localhost:6325/entityController/search?name=Copy the code

The search results are as follows:

Of the 5 records inserted just now, four records containing the keyword “Nanjing” have been searched!

Here is standard participle way, of course, every Chinese will be as a term, and that the “south”, “jing” keyword records were searched out, just different from scoring, of course, some of the other segmentation way, need the support of other participle plug-in, temporarily not involved here, in this paper, then do.