<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.74version>
dependency>
dependencies>
注意的是:elasticSearch的版本如果与客户端不一致需要自定义版本
注意添加注解 @Configuration,这样可以通过@Autowired来注入
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
);
return client;
}
}
1.创建索引
需要注入RestHighLevelClient
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
void testCreateIndex() throws IOException {
CreateIndexRequest indexRequest = new CreateIndexRequest("wang_index");
CreateIndexResponse response = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
}
若索引存在则返回true,不存在则false
@Test
void ExistIndex() throws IOException{
GetIndexRequest request=new GetIndexRequest("wang_index");
boolean exists = restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
System.out.println(exists);
}
@Test
void delIndex()throws IOException{
DeleteIndexRequest request=new DeleteIndexRequest("wang_index");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
}
注意观察返回对象与在可视化页面操作删除索引的过程是对应的上的。
测试:
发现索引已经删除
1.添加文档
新建实体类User并且导入AlibabaFastJson的依赖
@Test
void addDocument() throws IOException{
//创建对象
User user=new User("wangcj",23);
//创建请求
IndexRequest request=new IndexRequest("wang_index");
//规则:put/wang_index/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
// request.timeout("1");
//将数据放入到Json
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求,获取响应结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.status()+response.toString());
}
}
@Test
//规则:get/index/_doc/1
void existDocument() throws IOException{
GetRequest getRequest=new GetRequest("wang_index","1");
getRequest.storedFields("name","age");
//不返回上下文的内容
getRequest.fetchSourceContext(new FetchSourceContext(false));
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
}
@Test
void getDocument() throws IOException{
GetRequest getRequest=new GetRequest("wang_index","1");
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields.getSourceAsString());//打印文档内容
System.out.println(documentFields);
//返回内容与命令一样
}
}
void updateDocument() throws IOException{
UpdateRequest updateRequest=new UpdateRequest("wang_index","1");
updateRequest.timeout("1s");
User user=new User("wangcj",25);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.status());
}
}
@Test
void deleteDocument() throws IOException{
DeleteRequest deleteRequest=new DeleteRequest("wang_index","1");
deleteRequest.timeout("1s");
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
}
6.批量插入
@Test
void bulkAddDocuments() throws IOException{//批量操作
BulkRequest bulkRequest=new BulkRequest();
List<User> users=new ArrayList<>();
users.add(new User("wangcjj",23));
users.add(new User("chenyh",21));
for (int i = 0; i < users.size(); i++) {
bulkRequest.add(new IndexRequest("wang_index")
.id(""+(i+1))
.source(JSON.toJSONString(users.get(i)),XContentType.JSON));
}
//批处理请求
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.hasFailures());//是否失败 false则代表没有失败
}
测试:
7.批量查询
//查询
//searchRequest搜索请求
//searchSourceBuild 条件构造
//highLightBuild 构建高亮
@Test
void bulkQueryDocument() throws IOException{//批量查询操作
SearchRequest searchRequest=new SearchRequest();
//构建搜索条件
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//查询条件我们可以使用QueryBuild工具来实现
//精确查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangcj");
//查询全部
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
searchSourceBuilder.timeout(TimeValue.MINUS_ONE);
searchSourceBuilder.query(matchAllQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(search.getHits()));
SearchHit[] hits = search.getHits().getHits();
for (SearchHit hit: hits
) {
System.out.println(hit.getSourceAsMap());
}
}