SpringBoot整合Elasticsearch7
2021-01-09 11:34
标签:unit override 方式 path sleep tor factor evel fileread SpringBoot连接ElasticSearch有以下种方式, Spring boot 2的spring-boot-starter-data-elasticsearch支持的Elasticsearch版本是2.X, Elasticsearch已迭代到7.X.X版本,建议使用high-level-client进行链接。 需要指定版本号 src/main/resources/es.txt 运行结果: SpringBoot整合Elasticsearch7 标签:unit override 方式 path sleep tor factor evel fileread 原文地址:https://www.cnblogs.com/tigerlion/p/12961737.html
pom.xml
存储的对象
package com.ah.es.pojo;
public class Book {
private Integer bookId;
private String name;
public Book() {
}
public Book(Integer bookId, String name) {
this.bookId = bookId;
this.name = name;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", name=" + name + "]";
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
EsEntity·Es保存的对象
package com.ah.es.util;
public final class EsEntity
INDEX内容
{
"properties": {
"id":{
"type":"integer"
},
"bookId":{
"type":"integer"
},
"name":{
"type":"text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
EsUtil·工具类
package com.ah.es.util;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.*;
import org.elasticsearch.action.search.*;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.*;
import org.elasticsearch.search.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.*;
import java.util.*;
@Component
public class EsUtil {
@Value("192.168.16.128")
public String host;
@Value("9200")
public int port;
@Value("http")
public String scheme;
public static final String INDEX_NAME = "book-index";
public static String CREATE_INDEX;
public static RestHighLevelClient restClient = null;
private static String readFileToString(String filePath) {
File file = new File(filePath);
System.out.println(file.getAbsolutePath());
try (FileReader reader = new FileReader(file)) {
BufferedReader bReader = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = bReader.readLine()) != null) {
sb.append(s + "\n");
}
return sb.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
@PostConstruct
public void init() {
CREATE_INDEX = readFileToString("src/main/resources/es.txt");
System.out.println("CREATE_INDEX = " + CREATE_INDEX);
try {
if (restClient != null) {
restClient.close();
}
restClient = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, scheme)));
if (this.indexExist(INDEX_NAME)) {
return;
}
CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2));
request.mapping(CREATE_INDEX, XContentType.JSON);
CreateIndexResponse res = restClient.indices().create(request, RequestOptions.DEFAULT);
if (!res.isAcknowledged()) {
throw new RuntimeException("初始化失败");
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public boolean indexExist(String index) throws Exception {
GetIndexRequest request = new GetIndexRequest(index);
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
return restClient.indices().exists(request, RequestOptions.DEFAULT);
}
public IndexResponse insertOrUpdateOne(String index, EsEntity entity) {
IndexRequest request = new IndexRequest(index);
request.id(entity.getId());
request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
try {
return restClient.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public BulkResponse insertBatch(String index, List
ES调用方
package com.ah.es;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ah.es.pojo.Book;
import com.ah.es.util.*;
import java.util.*;
@Component
public class EsService {
@Autowired
private EsUtil esUtil;
public List
测试类
package com.ah.es;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.ah.es.pojo.Book;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {
@Autowired
private EsService bookService;
@Test
public void testAll() throws InterruptedException {
t1AddOne();
t2AddBatch();
Thread.sleep(1000);
t3FindAll();
t4search();
t5deleteOne();
t6deleteBatch();
Thread.sleep(1000);
t7FindAll();
}
@Test
public void t1AddOne() {
IndexResponse putOne = bookService.putOne(new Book(1, "西游记"));
System.out.println("【1】putOne:" + putOne);
}
@Test
public void t2AddBatch() {
List
【1】putOne:IndexResponse[index=book-index,type=_doc,id=1,version=5,result=created,seqNo=51,primaryTerm=1,shards={"total":3,"successful":1,"failed":0}]
【2】putBatch:OK
【3】
↓↓↓findAll
Book [bookId=2, name=水浒传]
Book [bookId=3, name=三国演义]
Book [bookId=1, name=西游记]
↑↑↑findAll
【4】
Book [bookId=2, name=水浒传]
【4】getByBookId:Book [bookId=2, name=水浒传]
【5】deleteById:BulkIndexByScrollResponse[sliceId=null,updated=0,created=0,deleted=1,batches=1,versionConflicts=0,noops=0,retries=0,throttledUntil=0s]
【6】deleteBatch:OK
【7】
↓↓↓findAll
↑↑↑findAll
上一篇:python操作excel
下一篇:ensp设置web登录两台防火墙
文章标题:SpringBoot整合Elasticsearch7
文章链接:http://soscw.com/index.php/essay/41160.html