前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaRestClient操作Elasticsearch基本文档的CRUD

JavaRestClient操作Elasticsearch基本文档的CRUD

作者头像
用户9006224
发布2022-12-21 09:10:58
2630
发布2022-12-21 09:10:58
举报
文章被收录于专栏:cjz的专栏cjz的专栏

导包

因为我用的springboot做的测试

代码语言:javascript
复制
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
         <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.4.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

application.yml配置

集群配置,这里主要是为了SpringDataElasticsearch

代码语言:javascript
复制
spring:
  data:
    elasticsearch:
      cluster-name: text-elastic #集群名称
      cluster-nodes: 127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303 #有多少机器,写多少

新增方法

代码语言:javascript
复制
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
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.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Esdemo1 {

    private RestHighLevelClient client;

    private Gson gson = new Gson();
    
    /**
     * 先执行
     */
    @Before
    public void init (){
        // 初始化HighLevel客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        HttpHost.create("http://127.0.0.1:9201"),
                        HttpHost.create("http://127.0.0.1:9202"),
                        HttpHost.create("http://127.0.0.1:9203")
                )
        );
    }
    
/*
*	新增文档
*/
    @Test
    public void testAddIndex() throws IOException {
        // 准备文档数据:
        Item item = new Item(1L, "小米手机9", " 手机","小米", 3499.00, "http://image.csdn.com/13123.jpg");
        // 转为Json格式:
        String toJson = gson.toJson(item);
        // 创建一个新增索引的请求,并指定是JSON格式
        IndexRequest indexRequest = new IndexRequest("索引名", "类型名", item.getId().toString()).source(toJson, XContentType.JSON);
        // 发起请求
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println("Response:"+indexResponse);
    }

    /**
     * 后执行
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

查看文档

代码语言:javascript
复制
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
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.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Esdemo1 {

    private RestHighLevelClient client;

    private Gson gson = new Gson();
    /**
     * 先执行
     */
    @Before
    public void init (){
        // 初始化HighLevel客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        HttpHost.create("http://127.0.0.1:9201"),
                        HttpHost.create("http://127.0.0.1:9202"),
                        HttpHost.create("http://127.0.0.1:9203")
                )
        );
    }

    /**
     * 查看文档
     */
    @Test
    public void testFindIndex() throws IOException {
        // 创建get请求,并指定id
        GetRequest getRequest = new GetRequest("索引名","类型名","1");
        // 查询,得到响应
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        // 解析响应,应该是json
        String source = response.getSourceAsString();
        //json转对象
        Item item = gson.fromJson(source, Item.class);
        //打印
        System.out.println("item::"+item);
    }

    /**
     * 后执行
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

修改文档

新增时,如果传递的id是已经存在的,则会完成修改操作,如果不存在,则是新增

代码语言:javascript
复制
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
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.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Esdemo1 {

    private RestHighLevelClient client;

    private Gson gson = new Gson();
    
    /**
     * 先执行
     */
    @Before
    public void init (){
        // 初始化HighLevel客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        HttpHost.create("http://127.0.0.1:9201"),
                        HttpHost.create("http://127.0.0.1:9202"),
                        HttpHost.create("http://127.0.0.1:9203")
                )
        );
    }
    
/*
*	新增时,如果传递的id是已经存在的,则会完成修改操作,如果不存在,则是新增
*/
    @Test
    public void testAddIndex() throws IOException {
        // 准备文档数据:
        Item item = new Item(1L, "小米手机9", " 手机","小米", 3499.00, "http://image.csdn.com/13123.jpg");
        // 转为Json格式:
        String toJson = gson.toJson(item);
        // 创建一个新增索引的请求,并指定是JSON格式
        IndexRequest indexRequest = new IndexRequest("索引名", "类型名", item.getId().toString()).source(toJson, XContentType.JSON);
        // 发起请求
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println("Response:"+indexResponse);
    }

    /**
     * 后执行
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

删除文档

代码语言:javascript
复制
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
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.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Esdemo1 {

    private RestHighLevelClient client;

    private Gson gson = new Gson();
    /**
     * 先执行
     */
    @Before
    public void init (){
        // 初始化HighLevel客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        HttpHost.create("http://127.0.0.1:9201"),
                        HttpHost.create("http://127.0.0.1:9202"),
                        HttpHost.create("http://127.0.0.1:9203")
                )
        );
    }

    /**
     * 删除文档
     */
    @Test
    public void testDeleteIndex() throws IOException {
        //创建删除请求,传入id
        DeleteRequest deleteRequest = new DeleteRequest("索引名","类型名","1");
        // 发起请求
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        //打印
        System.out.println("response = " + deleteResponse);
    }

    /**
     * 后执行
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-11-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 导包
  • application.yml配置
  • 新增方法
  • 查看文档
  • 修改文档
  • 删除文档
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com