微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

原生JAVA操作 Elasticsearch文档

package com.yqq.app13;

import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
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.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * @Author yqq
 * @Date 2021/11/30 16:26
 * @Version 1.0
 */
public class DocumentTest {
    RestHighLevelClient client;
    @Before
    public void init(){
        // 创建客户端对象,链接ES
        client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("node0",9200,"http")));
    }
    //新增/修改文档
    @Test
    public void addOrUpdateDocument(){
        //创建请求对象
        IndexRequest request = new IndexRequest("student").id("2");
        try {
            request.source(XContentFactory.jsonBuilder()
            .startObject()
            .field("id",2)
            .field("name","乔丹")
            .field("info","NBA公牛队最伟大篮球巨星")
            .endobject());
        } catch (IOException e) {
            e.printstacktrace();
        }
        //发送请求
        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
    // 根据id查询文档
    @Test
    public void findById() throws Exception{
        //创建请求对象
        GetRequest request = new GetRequest("student","2");
        //发送请求
        GetResponse response = client.get(request,RequestOptions.DEFAULT);
        //输出查询结果
        System.out.println(response.getSourceAsstring());
    }
    // 删除文档
    @Test
    public void deleteDocument() throws Exception{
        //创建请求对象
        DeleteRequest request = new DeleteRequest("student","2");
        //发送请求
        client.delete(request,RequestOptions.DEFAULT);
    }
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐