Springboot integra el uso de elasticSearch y API
dependencia de maven
<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Springboot usa la versión 6.8.5.
Se deben especificar otras versiones
inicialización
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
}
}
Si se trata de un clúster, utilice el siguiente código
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
}
}
API relacionada con el índice
- Crear índice
public class EsTest{
@Resource
private RestHighLevelClient client;
@Test
public void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("test_index");
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response);
}
}
- Determine si el índice existe
GetIndexRequest request = new GetIndexRequest("test_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
- Eliminar índice
DeleteIndexRequest request = new DeleteIndexRequest("test_index");
client.indices().delete(request, RequestOptions.DEFAULT);
API relacionada con el documento
- Crear documento
@Test
public void testCreateDocument() throws IOException {
EsUser user = new EsUser("盖伦", 28, "我有一个大保健");
IndexRequest request = new IndexRequest("index_test");
request.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
System.out.println(index.toString());;
}
resultado:
IndexResponse[index=index_test,type=_doc,id=DkfxKHcBDAil241A0UJ4,version=1,result=created,seqNo=9,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
- Comprueba si el documento existe
@Test
public void testIsExitDocument() throws IOException {
// 索引库,文档id
GetRequest request = new GetRequest("index_test", "DkfxKHcBDAil241A0UJ4");
// 不获取_source上下文
request.fetchSourceContext(new FetchSourceContext(false));
boolean exists = client.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
- Obtener información del documento
@Test
public void testSearchDocument() throws IOException {
GetRequest request = new GetRequest("index_test", "DkfxKHcBDAil241A0UJ4");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
System.out.println(response.toString());
}
resultado:
{"age":28,"desc":"我有一个大保健","name":"盖伦"}
{"_index":"index_test","_type":"_doc","_id":"DkfxKHcBDAil241A0UJ4","_version":1,"_seq_no":9,"_primary_term":1,"found":true,"_source":{"age":28,"desc":"我有一个大保健","name":"盖伦"}}
-
Eliminar y actualizar documentos
Eliminar usar DeleteRequest
Actualizar usar UpdateRequest -
Procesamiento por lotes
@Test
public void testESList() throws IOException {
BulkRequest request = new BulkRequest();
// 设置超时时间
request.timeout(new TimeValue(10, TimeUnit.SECONDS));
List<EsUser> userList = new ArrayList<>();
userList.add(new EsUser("蛮王", 22, "我的光辉时刻实在开大招的时候"));
userList.add(new EsUser("赵信", 40, "一点寒芒先至,随后抢出如龙"));
userList.add(new EsUser("剑圣", 212, "啦啦啦啊"));
userList.add(new EsUser("兔宝宝", 2, "我是一直兔宝宝"));
for (int i = 0; i < userList.size(); i++) {
request.add(
// 批量删除、修改 在这里修改对应的请求
new IndexRequest("index_test")
.id((i + 1) + "")
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
// 是否失败,返回false 代表执行成功
boolean b = responses.hasFailures();
}
- Preguntar
@Test
public void testSearch() throws IOException {
SearchRequest request = new SearchRequest("index_test");
// 查询构建器
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "赵信");
searchSourceBuilder.query(matchQuery);
searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
request.source(searchSourceBuilder);
SearchResponse search = client.search(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(search.getHits()));
System.out.println("===================");
for (SearchHit documentFields : search.getHits().getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}