ElasticSearch7.3 JAVA API查询 删除

在7.3版本中,已经不推荐使用TransportClient这个client,官网说在8.0以后的版本TransportClient将会被删除,并且推荐大家使用高阶版本的REST CLIENT -> RestHighLevelClient,本文使用的是7.3的RestHighLevelClient。

关于RestHighLevelClient,官网给的文档非常的详细,SO EASY。

本文只给出常用的查询和删除操作实例。

查询原始表结构如下:

CREATE TABLE `article` (
`id` varchar(255) NOT NULL,
`title` varchar(255) DEFAULT NULL,
`content` longtext,
`createdate` datetime DEFAULT NULL,
`editdate` datetime DEFAULT NULL,
`viewnums` int(11) DEFAULT '0',
`likenums` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

elasticsearch中的index如下

{
"mapping": {
"properties": {
"@timestamp": {
"type": "date"
},
"@version": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"content": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"createdate": {
"type": "date"
},
"editdate": {
"type": "date"
},
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"likenums": {
"type": "long"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"type": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"viewnums": {
"type": "long"
}
}
}
}
下面是SpringBoot工程中的Controller和Service,Service中包含了删除和查询的方法,以及注释。

Controller

package com.zzj.cloud.esclient.controller;


import com.zzj.cloud.esclient.services.ESRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class ESController {

@Autowired
private ESRestService esRestService;
@GetMapping("/")
public String all(){
String article = "";
article = esRestService.getStringById("","");
return article;
}
@GetMapping("/search")
public String search(String content ){
String article = "";
article = esRestService.searchArticle(content);
return article;
}
@GetMapping("/delete")
public long delete(String title ){
long deleteNum = esRestService.deleteArticle(title);
return deleteNum;
}

}
Service

package com.zzj.cloud.esclient.services;


import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;

import javax.websocket.ClientEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ESRestService {

private RestHighLevelClient client;
public ESRestService() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
//集群节点
// new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9200, "http")));
this.client = client;
}
public void shutdown(){
if(client!=null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 获取指定index和id的 数据
* @param index
* @param id
* @return
*/
public String getStringById(String index,String id){
String s = "";
id = "".equals(id)?"CW0sb2wBYtyF3syfPTY8":id;
index = "".equals(index)?"article-2019.08.08.03":index;
GetRequest getRequest = new GetRequest(index,id);
GetResponse response = null;
try {
response = this.client.get(getRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
//按字段Key获取对应的值
//DocumentField field = response.getField("content");
//获取全部的map,除了正常的值之外,会存在key是@version和@timestamp的值
Map<String, Object> source = response.getSource();
s = (String) source.get("content");
return s;
}

/**
* 根据指定的内容,查询所有Doc。
* @param content
* @return
*/
public String searchArticle(String content){
String article = "";
//// QueryBuilder qb= QueryBuilders.boolQuery().must(QueryBuilders.termQuery("title","JAVA开发工程师")).must(QueryBuilders.termQuery("age",30)) ;
// //精确查询
//// QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", content);
// //模糊查询
// QueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery("content", content);
//// matchQueryBuilder.
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//// sourceBuilder.query(QueryBuilders.termQuery("content", content));
// sourceBuilder.query(matchQueryBuilder);
// sourceBuilder.from(0);
// sourceBuilder.size(100);
// sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("article-2019.08.08.03");
// searchRequest.source(sourceBuilder);
// SearchResponse searchResponse;
// List<Map<String,Object>> list = new ArrayList<>();
//
// try {
// searchResponse = this.client.search(searchRequest,RequestOptions.DEFAULT);
// SearchHits searchHits = searchResponse.getHits();
// for(SearchHit hit:searchHits.getHits()){
// System.out.println( hit.getSourceAsString());
// list.add(hit.getSourceAsMap());
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
SearchHits searchHits = search("article-2019.08.08.03","content",content);
List<Map<String,Object>> list = new ArrayList<>();
for(SearchHit hit:searchHits.getHits()){
System.out.println( hit.getSourceAsString());
list.add(hit.getSourceAsMap());
}
article = list.toString();
return article;
}
public SearchHits search(String index,String key,String value){
QueryBuilder matchQueryBuilder = QueryBuilders.matchPhraseQuery(key, value);
// matchQueryBuilder.
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.query(QueryBuilders.termQuery("content", content));
sourceBuilder.query(matchQueryBuilder);
sourceBuilder.from(0);
sourceBuilder.size(100);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse;
List<Map<String,Object>> list = new ArrayList<>();
SearchHits searchHits = null;
try {
searchResponse = this.client.search(searchRequest,RequestOptions.DEFAULT);
searchHits = searchResponse.getHits();
for(SearchHit hit:searchHits.getHits()){
System.out.println( hit.getSourceAsString());
list.add(hit.getSourceAsMap());
}
} catch (IOException e) {
e.printStackTrace();
}
return searchHits;
}

public long deleteArticle(String titleName){
long deleteNum = 0l;

SearchHits searchHits = search("article-2019.08.08.03","title",titleName);
System.out.println("Exxcute Start" );
deleteCommon(searchHits);
//deleteAsync(searchHits);
System.out.println("Exxcute Done" );
return deleteNum;

}

/**
* 正常删除
* @param searchHits
*/
private void deleteCommon (SearchHits searchHits){
DeleteRequest deleteRequest = new DeleteRequest();
for(SearchHit hit:searchHits.getHits()) {
deleteRequest = new DeleteRequest("article-2019.08.08.03",hit.getId());
try {
DeleteResponse deleteResponse = this.client.delete(deleteRequest,RequestOptions.DEFAULT);
System.out.println("Delete Done【"+deleteResponse.getId()+"】,Status:【" + deleteResponse.status() + "】");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 异步删除
* @param searchHits
*/
private void deleteAsync (SearchHits searchHits) {
DeleteRequest deleteRequest = new DeleteRequest();
for(SearchHit hit:searchHits.getHits()){
deleteRequest = new DeleteRequest("article-2019.08.08.03",hit.getId());


//异步删除
this.client.deleteAsync(deleteRequest, RequestOptions.DEFAULT, new ActionListener<DeleteResponse>() {
@Override
public void onResponse(DeleteResponse deleteResponse) {
RestStatus restStatus = deleteResponse.status();
int status = restStatus.getStatus();
deleteResponse.getId();
System.out.println("Delete Done【"+deleteResponse.getId()+"】,Status:【" + status + "】");
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
System.out.println("ERROR " + hit.getId());
}
});
}

}
}
POM文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zzj.cloud</groupId>
<artifactId>esclient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>esclient</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--根据官网的解释说明,在后续的8.0之后,不再提供TransportClient方法访问ES-->
<!--<dependency>-->
<!--<groupId>org.elasticsearch.client</groupId>-->
<!--<artifactId>transport</artifactId>-->
<!--<version>7.3.0</version>-->
<!--</dependency>-->
<!--官网提供的The High Level Java REST Client-->
<!--依赖下面个包-->
<!--org.elasticsearch.client:elasticsearch-rest-client-->
<!--org.elasticsearch:elasticsearch-->
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client -->
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.3.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.3.0</version>
</dependency>

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
 

当然,这个API还包含了各种API操作,此处不做解释,请参考官网。


————————————————
版权声明:本文为CSDN博主「Sail__」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/diaobatian/article/details/98937406

原文地址:https://www.cnblogs.com/wangwenlong8/p/13022083.html