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 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> 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> 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> 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() {
                @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文件如下:



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.7.RELEASE
		 
	
	com.zzj.cloud
	esclient
	0.0.1-SNAPSHOT
	esclient
	Demo project for Spring Boot

	
		1.8
	

	
		
			
			
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
		
			
			
			
		
        
        
        
        
        
        
        
            org.elasticsearch
            elasticsearch
            7.3.0
        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            7.3.0
        

        
			org.elasticsearch.client
			elasticsearch-rest-high-level-client
			7.3.0
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


 

 

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

完毕。

 

 

你可能感兴趣的:(elasticsearch,JAVA,ELK搭建及使用)