Elasticsearch入门(四)JavaAPI(索引、文档操作)

通过 Java API 的方式对 Elasticsearch 服务进行访问。

项目搭建:

新建一个SpringBoot项目。pom文件:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

测试索引操作

package com.fan.esjavaapi.index;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

public class IndexDemo {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        createIndex(esClient);
        SelectIndex(esClient);
        DelIndex(esClient);
        esClient.close();
    }
    public static void createIndex(RestHighLevelClient esClient){
        //创建 user 索引
        CreateIndexRequest request = new CreateIndexRequest("user");
        {
            try {
                CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);
                //响应状态
                boolean acknowledged = createIndexResponse.isAcknowledged();
                System.out.println("创建索引:"+acknowledged);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //查看索引
    public static void SelectIndex(RestHighLevelClient esClient){
        GetIndexRequest request = new GetIndexRequest("user");
        {
            try {
                GetIndexResponse getIndexResponse =
                        esClient.indices().get(request, RequestOptions.DEFAULT);
                System.out.println("查询索引:");
                //响应状态
                System.out.println(getIndexResponse.getAliases());
                System.out.println(getIndexResponse.getMappings());
                System.out.println(getIndexResponse.getSettings());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 删除索引
    public static void DelIndex(RestHighLevelClient esClient){
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        {
            try {
                //删除索引
                AcknowledgedResponse response =
                        esClient.indices().delete(request, RequestOptions.DEFAULT);
                //响应状态
                System.out.println("删除:"+response.isAcknowledged());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

注意:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名

总结

关于索引的请求,用到 xxxIndexRequest 以及 .indices().xxx,其中 xxx 代表增删查

测试文档操作 

创建一个实体类:User

package com.fan.esjavaapi.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.annotation.AliasFor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private String sex;
    private Integer age;
}

测试类:

package com.fan.esjavaapi.estest;

import com.fan.esjavaapi.bean.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Arrays;

public class DocDemo {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        createDoc(esClient);
        esClient.close();
    }
    public static void createDoc(RestHighLevelClient esClient) throws IOException {
        //插入数据
        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
        User user = new User();
        user.setName("zhangsan");
        user.setAge(20);
        user.setSex("男");
        //向ES插入数据,必须将数据转换为JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
    }
    public static void updateDoc(RestHighLevelClient esClient) throws IOException {
        //修改数据
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("1001");
        request.doc(XContentType.JSON,"sex","女");
        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        esClient.close();
    }
    public static void selectDoc(RestHighLevelClient esClient) throws IOException {
        //查询数据
        GetRequest request = new GetRequest();
        request.index("user").id("1001");
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        esClient.close();
    }
    public static void delDoc(RestHighLevelClient esClient) throws IOException {
        //删除数据
        DeleteRequest request = new DeleteRequest();
        request.index("user").id("1001");
        DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        esClient.close();
    }
    public static void  InsertBatchNotUser(RestHighLevelClient esClient) throws IOException {
        //批量插入数据,非实体
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","zhangsan"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","lisi"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","wangwu"));
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON,"name","lucy"));
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
        esClient.close();
    }
    public static void  InsertBatchIsUser(RestHighLevelClient esClient) throws IOException {
            //批量插入数据,实体
        BulkRequest request = new BulkRequest();
        // 创建数据对象
        User user1 = new User("可乐1","男",18);
        User user2 = new User("可乐2","男",19);
        User user3 = new User("可乐3","男",20);
        User user4 = new User("可乐4","男",21);
        User user5 = new User("可乐5","男",22);
        User user6 = new User("可乐6","男",23);
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, user1));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, user2));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, user3));
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, user4));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, user5));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, user6));
        // 客户端发送请求,获取响应对象
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println("响应时间:" + response.getTook());
        System.out.println("创建的内容:" + Arrays.toString(response.getItems()));
        // 关闭 ES 客户端
        esClient.close();
    }
    public static void  DelBatch(RestHighLevelClient esClient) throws IOException {
        BulkRequest request = new BulkRequest();
        //配置修改参数
        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));
        request.add(new DeleteRequest().index("user").id("1004"));
        request.add(new DeleteRequest().index("user").id("1005"));
        //客户端发送请求,获取响应对象
        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        System.out.println("响应时间:"+response.getTook());
        esClient.close();
    }

}

总结

增删改查文档操作格式:

  • 连接 ES 客户端
  • 创建一个 XXXRequest 对象,其中 XXX 代表增删改查
  • 给该对象设置索引和文档
  • 调用 .XXX请求,传入参数,其中 XXX 代表增删改查
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值