栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

原生JAVA操作 Elasticsearch文档

原生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;


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618582.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号