We explained in the last article elasticsearch Installation of , Let's do it this time , How to integrate in your own project elasticsearch.
Normally speaking spring-data The corresponding starter, Let's use a variety of Template Operate the corresponding component , For example, commonly used RedisTemplate,
JdbcTemplate etc. , actually spring-data The corresponding elasticsearch Corresponding tools for . But I don't use it here , It's direct use elasticsearch Primordial api Realized . Why do you do that , because spring-data-elasticsearch
Latest version 3.2, Top supported elasticsearch Version is 6.8, And we use it 7.2 Version of , And we're officially advised to use it jar The version should be consistent with the software version .


There is another problem , It's about the client , spring-data-elasticsearch Is used by default in TransportClient,
This client is in 7 This version is no longer recommended , And will be in 8 Completely removed from the version of . And we use it 7 This version , Currently recommended elasticsearch Advanced client for ,HighLevelRestClient.
spring-data-es We will always support it TransportClient, Just your one es Version support . of course ,spring-data-es It also supports high-level clients , But there is also the problem of low support version , So I finally decided to use the native client . If you use it es The version is relatively low , It can still be used spring-data-es Of .

Next, let's integrate the project , Before integration , You need to know es Some proper nouns in , For example, what is an index , type , file , At the same time, you need to understand es What is it for .es The main function is to query , That is to say, he is very fast in searching things , And support participle , Full text search . If we were mysql Look up the content of the article , In fact, it is very painful , We may have to use it
like Or splicing or To query multiple fields , And some scenarios are impossible to implement , For example, the content of your article contains ” A flower “, And you search ” A flower “
You can't find out about this , however es sure , because es Can be participle , He can have a flower , Share   ” One “  ” flower “ Two words , And then ” A flower “ Share   ” One “ and ” flower “ 
( notes : This is for personal convenience , Maybe the specific participle is not so divided , We understand the essence ). It is easy to query .
meanwhile es The query is faster , It's also because of his internal flashback index , On the principle of flashback index , You can look for information , I don't want to talk about it here .


One . introduce jar package
<dependency> <groupId>org.elasticsearch.client</groupId>
<version>7.2.0</version> </dependency> <dependency>
<artifactId>elasticsearch-rest-client</artifactId> <version>7.2.0</version>
</dependency> <dependency> <groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId> <version>7.2.0</version> </dependency>

Two . Encapsulation tool class , High level client encapsulation is mainly used here , It mainly encapsulates the creation of indexes , Determine whether the index exists , Drop index , Insert document function , There are still some advanced features not yet available
End of study , Such as highlighting and paging , I'll update as I research , Here are some simple operations demo. The following articles are in-depth .
@Component @Slf4j public class EsUtil { @Resource private RestHighLevelClient
restHighLevelClient; /** * Create index ( The default number of slices is 5 And the number of copies is 1) * @param indexName * @throws
IOException */ public boolean createIndex(String indexName) throws IOException
{ CreateIndexRequest request = new CreateIndexRequest(indexName);
request.settings(Settings.builder() // Set the number of slices to 3, The copy is 2
.put("index.number_of_shards", 3) .put("index.number_of_replicas", 2) );
request.mapping(generateBuilder()); CreateIndexResponse response =
restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); //
Indicates whether all nodes have acknowledged the request boolean acknowledged = response.isAcknowledged(); //
Indicates whether the required number of sharded copies is started for each fragment in the index before the timeout boolean shardsAcknowledged =
response.isShardsAcknowledged(); if (acknowledged || shardsAcknowledged) {
log.info(" Index created successfully ! The index name is {}", indexName); return true; } return false; } /** *
Determine whether the index exists * @param indexName * @return */ public boolean isIndexExists(String
indexName){ boolean exists = false; try { GetIndexRequest getIndexRequest = new
GetIndexRequest(indexName); getIndexRequest.humanReadable(true); exists =
restHighLevelClient.indices().exists(getIndexRequest,RequestOptions.DEFAULT); }
catch (IOException e) { e.printStackTrace(); } return exists; } /** * Drop index *
@param indexName * @return */ public boolean delIndex(String indexName){
boolean acknowledged = false; try { DeleteIndexRequest deleteIndexRequest = new
AcknowledgedResponse delete =
RequestOptions.DEFAULT); acknowledged = delete.isAcknowledged(); } catch
(IOException e) { e.printStackTrace(); } return acknowledged; } /** *
Update index ( The default number of slices is 5 And the number of copies is 1): * You can only add some nonexistent fields to the index * Existing mapping cannot be changed * * @param clazz
Automatic mapping based on entity es Indexes * @throws IOException */ public boolean updateIndex(Class clazz)
throws Exception { Document declaredAnnotation = (Document
)clazz.getDeclaredAnnotation(Document.class); if(declaredAnnotation == null){
throw new Exception(String.format("class name: %s can not find Annotation
[Document], please check", clazz.getName())); } String indexName =
declaredAnnotation.index(); PutMappingRequest request = new
PutMappingRequest(indexName); request.source(generateBuilder(clazz));
AcknowledgedResponse response =
restHighLevelClient.indices().putMapping(request, RequestOptions.DEFAULT); //
Indicates whether all nodes have acknowledged the request boolean acknowledged = response.isAcknowledged(); if
(acknowledged ) { log.info(" Index updated successfully ! The index name is {}", indexName); return true; }
return false; } /** * Add a single piece of data * Provide a variety of ways : * 1. json * 2. map * Map<String, Object>
jsonMap = new HashMap<>(); * jsonMap.put("user", "kimchy"); *
jsonMap.put("postDate", new Date()); * jsonMap.put("message", "trying out
Elasticsearch"); * IndexRequest indexRequest = new IndexRequest("posts") *
.id("1").source(jsonMap); * 3. builder * XContentBuilder builder =
XContentFactory.jsonBuilder(); * builder.startObject(); * { *
builder.field("user", "kimchy"); * builder.timeField("postDate", new Date()); *
builder.field("message", "trying out Elasticsearch"); * } *
builder.endObject(); * IndexRequest indexRequest = new IndexRequest("posts") *
.id("1").source(builder); * 4. source: * IndexRequest indexRequest = new
IndexRequest("posts") * .id("1") * .source("user", "kimchy", * "postDate", new
Date(), * "message", "trying out Elasticsearch"); * * report errors : Validation Failed: 1:
type is missing; * Add two jar Package solution * * @return */ public IndexResponse add(String
indexName, Object o) throws IOException { IndexRequest request = new
IndexRequest(indexName); String userJson = JSON.toJSONString(o);
request.source(userJson, XContentType.JSON); IndexResponse indexResponse =
restHighLevelClient.index(request, RequestOptions.DEFAULT); return
indexResponse; } private XContentBuilder generateBuilder() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject();
{ builder.startObject("properties"); { // es7 And later removed the mapping type --person
builder.startObject("name"); { builder.field("type", "text");
builder.field("analyzer", "ik_smart"); } builder.endObject(); } {
builder.startObject("age"); { builder.field("type", "integer"); }
builder.endObject(); } { builder.startObject("desc"); { builder.field("type",
"text"); builder.field("analyzer", "ik_smart"); } builder.endObject(); } {
builder.startObject("id"); { builder.field("type", "integer"); }
builder.endObject(); } builder.endObject(); } builder.endObject();
/*.startObject().field("properties") .startObject().field("person")
.startObject("name") .field("type" , "text") .field("analyzer", "ik_smart")
.endObject() .startObject("age") .field("type" , "int") .endObject()
.startObject("desc") .field("type", "text") .field("analyzer", "ik_smart")
.endObject() .endObject() .endObject();*/ return builder; } }
The index structure given in the above tool class is a user , only id, name , age, desc Structure of four simple fields

meanwhile desc Both the field and the name field are used ik-smart Do participle .


Then you can use it controller perhaps junittest To make the call , coordination head Plug in observation data . The general process is ,
index Define index structure , Then we save the formatted data to es in , use es Efficient delivery api To make inquiries .
This article comes here first , In fact, there is a pain point here, if our data structure is more complex , Then we may need to write a lot of code when creating the index , That's all four fields


So here we can design the index structure automatically according to the structure of the entity , image spring-data-es According to our annotation on the entity class , Automatically indexed . I also implement custom annotations here to create es The method of index structure , The next article will introduce you .














©2019-2020 Toolsou All rights reserved,
CCTV :Tiktok A lawsuit shows the attitude and determination of safeguarding rights C Language confession practice small program ( Suitable for beginners )mysql Recursively finds all child nodes of the parent class Linux File name validity detection c Language rose advertising code about Bellman-Ford Personal understanding of algorithms Hackbar Using the tutorial ( Essence )2020 year 6 month 26 day C# Class library read json Profile help class Vue + Element-ui Drop down box for el-select Get extra parameters Go language Array initialization and basic operations