Elasticsearch Java REST Client 入门使用

简介

Java REST Client 有两种:

  • Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。
  • Java High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供很多API,并负责请求的编排与响应的反编排。

注: 在 Elasticsearch 7.0 中不建议使用TransportClient,并且在8.0中会完全删除TransportClient。因此,官方更建议我们用Java High Level REST Client,它执行HTTP请求,而不是序列号的
Java请求。

环境配置

  • Maven configuration

我这里使用的是7.2.0版本的Elasticsearch,说以对应使用7.2.0版本的REST Clien。

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.2.0</version>
</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.2.0</version>
</dependency>
  • 初始化得到一个RestHighLevelClient实例
RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")
            ));

入门使用

  • 创建索引库
public void testCreatIndex() throws IOException {
        //创建索引对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("xc_course");
        //设置参数
        createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0"));
        //指定映射
        createIndexRequest.mapping("{
" +
                "  "properties": {
" +
                "    "name": {
" +
                "      "type": "text",
" +
                "      "analyzer": "ik_max_word",
" +
                "      "search_analyzer": "ik_smart"
" +
                "    },
" +
                "    "description": {
" +
                "      "type": "text",
" +
                "      "analyzer": "ik_max_word",
" +
                "      "search_analyzer": "ik_smart"
" +
                "    },
" +
                "    "studymodel": {
" +
                "      "type": "keyword"
" +
                "    },
" +
                "    "price": {
" +
                "      "type": "float"
" +
                "    },
" +
                "    "timestamp": {
" +
                "      "type": "date",
" +
                "      "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
" +
                "    }
" +
                "  }
" +
                "}", XContentType.JSON);
        //操作索引的客户端
        IndicesClient indices = client.indices();
        //执行创建索引库
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        //得到响应
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    }
  • 添加文档
    // 添加文档
    @Test
    public void testIndex() throws IOException {
        //文档内容
        //准备json数据
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "spring cloud实战");
        jsonMap.put("description", "本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心eureka。");
        jsonMap.put("studymodel", "201001");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonMap.put("timestamp", dateFormat.format(new Date()));
        jsonMap.put("price", 5.6f);
        IndexRequest indexRequest = new IndexRequest("xc_course").id("1").source(jsonMap);
        client.index(indexRequest, RequestOptions.DEFAULT);
        client.close();

    }
  • 获取文档
// 搜索文档
    @Test
    public void testGetDoc() throws IOException {
        //查询请求对象

        GetRequest getRequest = new GetRequest(
                "xc_course",
                "1");

        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        //得到文档的内容
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        System.out.println(sourceAsMap);
    }
  • 删除索引库
// 删除索引库
    @Test
    public void testDeleteIndex() throws IOException {
        //删除索引对象
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course");
        //操作索引的客户端
        IndicesClient indices = client.indices();
        //执行删除索引
        AcknowledgedResponse acknowledgedResponse = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT);
        //得到响应
        boolean acknowledged = acknowledgedResponse.isAcknowledged();
        System.out.println(acknowledged);
    }

更多使用参考:[Java REST Client 官方文档]: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

原文地址:https://www.cnblogs.com/fate-pc/p/13305118.html