强强联手SpringBoot集成搜索引擎Elasticsearch
Elasticsearch(简称ES)是一个基于Lucene构建的开源搜索引擎。它提供了一个分布式、多租户的全文搜索引擎,能够快速、实时地存储、检索和分析大量的数据。Elasticsearch是Elastic公司(前身是Elasticsearch BV)开发的,并且是Elastic Stack的核心组件之一。
Spring家族作为当前Java的主流生态,其中的SpringBoot更是佼佼者,两者结合又该如何使用呢?一起来看看吧。
官方文档
首先我们查看官方文档
这里我们选择其他版本。选择7.6
我们一般使用高级的客户端
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
环境搭建
创建一个SpringBoot项目
所以我们要修改版本与我们的对应
编写配置类
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
}
索引API
创建索引
CreateIndexRequest request = new CreateIndexRequest("索引名");
client.indices().create(request, RequestOptions.DEFAULT);
create()
创建
//测试索引的创建 Request PUT kylin_index
@Test
void testCreateIndex() throws IOException {
//1.创建索引请求 put
CreateIndexRequest request = new CreateIndexRequest("kylin_index");
//2.客户端执行请求 IndicesClient,请求后获得响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
获取索引
new GetIndexRequest("索引名");
client.indices().exists(request, RequestOptions.DEFAULT);
exists()
判断是否存在返回boolean
//测试获取索引
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("kylin_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
删除索引
new DeleteIndexRequest("索引名");
client.indices().delete(request, RequestOptions.DEFAULT);
delete()
删除索引方法返回一个AcknowledgedResponse对象通过isAcknowledged()
判断是否被删除。
//删除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("kylin_index");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
文档API
当前所有的索引全都被删除。
创建一个User对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
导入fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
添加文档
XContentType.JSON
表示传送的是Json数据
//测试添加文档
@Test
void testAddDocument() throws IOException {
//创建对象
User user = new User("kylin", 3);
//创建请求
IndexRequest request = new IndexRequest("kylin_index");
//规则 put/kylin_index/_doc/1{user(json)}
request.id("1");
request.timeout("1s");//过期时间
//将我们的数据放入请求 json
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求获取响应结果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());
}
获取文档
判断该文档是否存在
_source就是下面这个数据,不获取。
//获取文档,判断是否存在 get /kylin_index/_doc/1
@Test
void testIsExists() throws IOException {
GetRequest getRequest = new GetRequest("kylin_index", "1");
//不获取返回的_source的上下文 2个可以不用配
getRequest.fetchSourceContext(new FetchSourceContext(false));
//将某字段单独存放在GetResponse对象
getRequest.storedFields("_none");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
获取文档信息
getSourceAsString()
获取_source中的内容以String类型
更新文档
//更新文档信息 PUT /kylin_index/1/_update{"doc":{}}
@Test
void testUpdateRequest() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("kylin_index", "1");
updateRequest.timeout("1s");
User user = new User("Kylin", 18);
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);//表明传的是json数据类型
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
删除文档
//测试删除文档信息 DELETE /kylin_index/1
@Test
void testDeleteRequest() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("kylin_index", "1");
deleteRequest.timeout("1s");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
批量操作
创建 BulkRequest对象BulkRequest bulkRequest = new BulkRequest();
client.bulk(bulkRequest, RequestOptions.DEFAULT);
bulkResponse.hasFailures()
判断是否失败
//批量插入数据
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("kylin1", 3));
userList.add(new User("kylin2", 3));
userList.add(new User("kylin3", 3));
userList.add(new User("kylin4", 3));
userList.add(new User("kylin5", 3));
userList.add(new User("kylin6", 3));
userList.add(new User("kylin7", 3));
//批处理请求
for (int i = 0; i < userList.size(); i++) {
bulkRequest.add(new IndexRequest("kylin_index").id("" + (i + 1)).source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());//false 是否失败,没有失败代表成功
}
其他的获取更新也类似该操作。
查询文档
创建搜索请求new SearchRequest("索引名");
构建搜索条件SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
- 查询条件,我们可以使用
QueryBuilders
工具来实现 QueryBuilders.termQuery
精确查询QueryBuilders.matchAllQuery()
匹配所有sourceBuilder.query(termQueryBuilder);
添加查询条件sourceBuilder.highlighter();
构建高亮
搜索请求添加搜索条件searchRequest.source(sourceBuilder);
客户端执行搜索client.search(searchRequest, RequestOptions.DEFAULT);
searchResponse.getHits().getHits()
获取hits
// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("kylin_index");
// 构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.highlighter();//高亮
// 查询条件,我们可以使用 QueryBuilders 工具来实现
// QueryBuilders.termQuery 精确
// QueryBuilders.matchAllQuery() 匹配所有
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name",
"kylin1");
// MatchAllQueryBuilder matchAllQueryBuilder =
QueryBuilders.matchAllQuery();
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//超时时间
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//hits
System.out.println(JSON.toJSONString(searchResponse.getHits()));
System.out.println("=================================");
for (SearchHit documentFields : searchResponse.getHits().getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}
到此为止,集成完成。
转载自:https://juejin.cn/post/7306407473280155685