Experimental environment
First of all, of course, you need to install the elasticsearch environment. It is best to install the visual plug-in elasticsearch-head to facilitate us to view data intuitively.
Of course, you can refer to my post in this part: "Elastic search installation and filling pits on centos7"
My ES is installed at http://113.209.119.170:9200/ (this address needs to be assigned to the springboot project)
Spring Project Creation
There is no special explanation for this part, but there are a few things to be careful about.
Note that when creating a new project, remember to check the Elasticsearch dependencies in web and NoSQL, and let’s take a picture to illustrate:
When creating a project, check the es dependency option in Nosql.
After the project is automatically generated, the dependency of spring-boot-starter-data-elasticsearch will be 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 restful es java client jest, so we also need to add jest dependencies 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, when starting the spring project, an error of JNA not found. native methods will be disabled.:
JNA not found. native methods will be disabled.
The es server address needs to be configured in the project configuration file application.yml
server: port: 6325spring: elasticsearch: jest: uris: - http://113.209.119.170:9200 # Address of ES server! read-timeout: 5000
Code Organization
My project code is organized as follows:
Project code organization
Each part of the code is explained as follows, and the comments are:
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.execute(index); LOGGER.info("ES Insert Complete"); } 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.execute(bulk.build()); LOGGER.info("ES Insert Complete"); } catch (IOException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } } /** * Search 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.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 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; }}Actual experiments
To add several pieces of data, you can use the postman tool or you can enter it directly in the browser, such as adding the following 5 pieces of data:
http://localhost:6325/entityController/save?id=1&name=Nanjing Sun Yat-sen Mausoleum http://localhost:6325/entityController/save?id=2&name=Nanjing Normal University in China 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=There seems that there is no city called Jing in the south of China.
The data insertion effect is as follows (using the visual plug-in elasticsearch-head):
Data insertion effect
Let's do a search test: For example, I want to search for the keyword "Nanjing"
We type in the browser:
http://localhost:6325/entityController/search?name=Nanjing
The search results are as follows:
Search results for keyword "Nanjing"
All four records with the keyword "Nanjing" inserted just now were searched!
Of course, the standard word segmentation method is used here, and each Chinese is used as a term. All records containing the keyword "South" and "Beijing" have been searched, but the scores are different. Of course, there are other word segmentation methods. At this time, the support of other word segmentation plug-ins is required. This is not covered here, and I will explore it later.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.