【Elasticsearch】- 使用JavaAPI操作elasticsearch

举报
1+1=王 发表于 2022/12/20 20:31:22 2022/12/20
【摘要】 【Elasticsearch】- 使用JavaAPI操作elasticsearch

@[TOC]

工程准备

创建maven工程并引入Elasticsearch相关依赖:

        <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.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

索引操作

创建索引

    @Test
    public void index_create_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //创建索引
        CreateIndexRequest request = new CreateIndexRequest("student");
        CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);

        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("响应状态:"+acknowledged);

        //关闭Elasticsearch客户端
        esClient.close();
    }

使用Postman测试索引是否成功:

在这里插入图片描述

查询索引

    @Test
    public void index_get_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //查询索引
        GetIndexRequest getIndexRequest = new GetIndexRequest("student");
        GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);

        System.out.println(getIndexResponse.getAliases());
        System.out.println(getIndexResponse.getMappings());
        System.out.println(getIndexResponse.getSettings());
        
        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

删除索引

    @Test
    public void index_delete_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //删除索引
        DeleteIndexRequest getIndexRequest = new DeleteIndexRequest("student");
        AcknowledgedResponse delete = esClient.indices().delete(getIndexRequest, RequestOptions.DEFAULT);

        System.out.println(delete.isAcknowledged());

        //关闭Elasticsearch客户端
        esClient.close();
    }

文档操作

进行文档操作前,先创建文档数据对应的java实体类Student:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
    private String name;
    private int age;
    private String sex;
    private String level;
}

添加文档数据

    @Test
    public void doc_insert_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        IndexRequest request = new IndexRequest();
        request.index("student").id("10000");

        Student student = new Student();
        student.setName("王同学");
        student.setAge(22);
        student.setSex("男");
        student.setLevel("研究生");

        ObjectMapper mapper = new ObjectMapper();
        String studentJson = mapper.writeValueAsString(student);

        request.source(studentJson, XContentType.JSON);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());

        //关闭Elasticsearch客户端
        esClient.close();
    }

批量添加文档数据

    @Test
    public void doc_insert_batch_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        BulkRequest request = new BulkRequest();

        request.add(new IndexRequest().index("student").id("10001").source(XContentType.JSON, "name", "张三"));
        request.add(new IndexRequest().index("student").id("10002").source(XContentType.JSON, "name", "李四"));
        request.add(new IndexRequest().index("student").id("10003").source(XContentType.JSON, "name", "王五"));

        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getItems());

        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

修改文档数据

@Test
    public void doc_update_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        UpdateRequest request = new UpdateRequest();
        request.index("student").id("10000");
        request.doc(XContentType.JSON,"sex","女");

        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());

        //关闭Elasticsearch客户端
        esClient.close();
    }

根据id查询文档数据

    @Test
    public void doc_search_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        GetRequest request = new GetRequest();
        request.index("student").id("10000");
        GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());

        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

查询当前索引所有文档数据

    @Test
    public void doc_search_all_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        SearchRequest request = new SearchRequest();
        request.indices("student");

        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for(SearchHit hit:hits){
            System.out.println(hit.getSourceAsString());
        }

        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

分页查询

    @Test
    public void doc_search_size_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        SearchRequest request = new SearchRequest();
        request.indices("student");

        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.from(0);
        builder.size(2);

        request.source(builder);

        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for(SearchHit hit:hits){
            System.out.println(hit.getSourceAsString());
        }

        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

模糊查询

    @Test
    public void doc_search_match_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        SearchRequest request = new SearchRequest();
        request.indices("student");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","王")));

        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        for(SearchHit hit:hits){
            System.out.println(hit.getSourceAsString());
        }

        //关闭Elasticsearch客户端
        esClient.close();
    }

在这里插入图片描述

删除文档数据

    @Test
    public void doc_delete_test() throws IOException {
        //创建Elasticsearch客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        DeleteRequest request = new DeleteRequest();
        request.index("student").id("10000");
        DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());

        //关闭Elasticsearch客户端
        esClient.close();
    }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。