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

一:MAVEN使用架包

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

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

二:源码

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();
			}
		}
    }
    
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值