ElasticSearch 使用JAVA做简单的增删查改

一:MAVEN使用架包

注意这里的架包版本号要与你的ElasticSerach版本一致

         
		    org.elasticsearch.client
		    elasticsearch-rest-high-level-client
		    7.2.0
		
	    
	        org.elasticsearch.client
	        transport
	        7.2.0
	    
		
		    org.elasticsearch
		    elasticsearch
		    7.2.0
		

二:源码

package com.xsd.elastic;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
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.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;


/**
 * 
 * @Descption: ElasticSearch 增删查改(异步)
 * @author: WEICY
 * @version: 7.2.0
 * @date: 2019年8月12日上午11:16:01
 */
public class ElasticSearchTest1 {
	
	public static void main(String[] args) {
		insertOrUpdate();	
	}
    
	/**
	 * 
	 * @Author: WEICY
	 * @Descption:查询
	 * @Date: 2019年10月8日 上午10:30:28
	 */
    @SuppressWarnings("deprecation")
	public static void search() {
    	RestHighLevelClient client = new RestHighLevelClient(
    			RestClient.builder(new HttpHost("IP", 9200, "http")));

        try {
        	//第一种查询方式
        	GetRequest request = new GetRequest("store", "books", "1");//INDEX TYPE ID
        	GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
			System.out.println("==============="+getResponse.getSourceAsMap());
			System.out.println("==============="+getResponse.getSourceAsString());
       
			System.out.println("-----------------------------------------------------------");
			//第二种查询方式
//			SearchSourceBuilder bilder=new SearchSourceBuilder();
			SearchRequest searchRequest = new SearchRequest("store");//搜索index
			SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT);
			//设置搜索Type
			searchRequest.types("books");
			
			//设置搜索INDEX
			System.out.println(response);
			System.out.println(response.getHits().getHits().clone()[1].getSourceAsMap());
        } catch (IOException e) {
			e.printStackTrace();
        }finally{
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
    

    /**
     * 
     * @Author: WEICY
     * @Descption: 新增或更新
     * @Date: 2019年10月8日 上午10:30:43
     */
    @SuppressWarnings("deprecation")
	public static void insertOrUpdate(){
    	RestHighLevelClient client = new RestHighLevelClient(
    			RestClient.builder(new HttpHost("IP", 9200, "http")));
    	IndexRequest request = new IndexRequest("posts","doc","1"); 
    	
    	String jsonString = "{" +
    	        "\"user\":\"kimchy\"," +
    	        "\"postDate\":\"2013-01-30\"," +
    	        "\"message\":\"trying out Elasticsearchs\"" +
    	        "}";
    	request.source(jsonString, XContentType.JSON);
    	
    	try {
    		IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
    		
    		String index = indexResponse.getIndex();
            String type = indexResponse.getType();
            String id = indexResponse.getId();
            long version = indexResponse.getVersion();
            if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
                System.out.println("添加成功");
                System.out.println("type:" + type);
                System.out.println("id:" + id);
                System.out.println("version:" + version);
                System.out.println("index:" + index);
            } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
                System.out.println("更新成功");
                System.out.println("index:" + index);
                System.out.println("type:" + type);
                System.out.println("id:" + id);
                System.out.println("version:" + version);
            }
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
	    	try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    
    /**
     * 
     * @Author: WEICY
     * @Descption: 删除
     * @Date: 2019年10月8日 上午10:31:59
     */
    @SuppressWarnings("deprecation")
	public static void delete(){
    	RestHighLevelClient client = new RestHighLevelClient(
    			RestClient.builder(new HttpHost("IP", 9200, "http")));
    	DeleteRequest request=new DeleteRequest("posts","doc","1");
    	
    	// 等待主分片可用的超时时间
        request.timeout(TimeValue.timeValueMinutes(10));
    	try {
			DeleteResponse deleteResponse=client.delete(request, RequestOptions.DEFAULT);
			
			if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
                System.out.println("未找到需要删除的文档!");
                return;
            }
			
			String index = deleteResponse.getIndex();
            String type = deleteResponse.getType();
            String id = deleteResponse.getId();
            long version = deleteResponse.getVersion();
            System.out.println("index:" + index + "; type:" + type + "; id:" + id + ",version:" + version);
            ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
            if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
                System.out.println("未完全执行所有分片,总分片数为:" + shardInfo.getTotal() + ",执行的分片数为:"+ shardInfo.getSuccessful());
            }
            if (shardInfo.getFailed() > 0) {
                for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                    String reason = failure.reason();
                    System.out.println("失败原因:" + reason);
                    return;
                }
            }
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
	    	try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    
}

 

你可能感兴趣的:(ElasticSearch)