首页 > 编程语言 >ElasticSearch Java API 基本操作

ElasticSearch Java API 基本操作

时间:2023-10-18 15:37:40浏览次数:46  
标签:info index indexName log Java API esClient 基本操作 String

前言

ElasticSearch Java API是ES官方在8.x版本推出的新java api,也可以适用于7.17.x版本的es。

本文主要参考了相关博文,自己手动编写了下相关操作代码,包括更新mappings等操作的java代码。

代码示例已上传github

版本

  1. elasticsearch版本:7.17.9,修改/elasticsearch-7.17.9/config/elasticsearch.yml,新增一行配置:xpack.security.enabled: false,避免提示
  2. cerebro版本:0.8.5(浏览器连接es工具)
  3. jdk版本:11
  4. elasticsearch-java版本:
<dependency>  
    <groupId>co.elastic.clients</groupId>  
    <artifactId>elasticsearch-java</artifactId>  
    <version>7.17.9</version>  
</dependency>  
  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.12.3</version>  
</dependency>

连接

public static ElasticsearchClient getEsClient(String serverUrl) throws IOException {  
    RestClient restClient = RestClient.builder(HttpHost.create(serverUrl)).build();  
    ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());  
    ElasticsearchClient esClient = new ElasticsearchClient(transport);  
    log.info("{}", esClient.info());  
    return esClient;  
}

索引

创建索引

public static void createIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
    if (existsIndex(esClient, indexName)) {  
        log.info("index name: {} exists!", indexName);  
    } else {  
        CreateIndexResponse response = esClient.indices().create(c -> c.index(indexName));  
        log.info("create index name: {}, ack: {}", indexName, response.acknowledged());  
    }  
}

// 判断索引是否存在
public static boolean existsIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
    BooleanResponse exists = esClient.indices().exists(c -> c.index(indexName));  
    return exists.value();  
}

查询索引

public static void getIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
    GetIndexResponse getIndexResponse = esClient.indices().get(s -> s.index(indexName));  
    Map<String, IndexState> result = getIndexResponse.result();  
    result.forEach((k, v) -> log.info("get index key: {}, value= {}", k, v));  
  
    // 查看全部索引  
    IndicesResponse indicesResponse = esClient.cat().indices();  
    indicesResponse.valueBody().forEach(i ->  
            log.info("get all index, health: {}, status: {}, uuid: {}", i.health(), i.status(), i.uuid()));  
}

删除索引

public static void delIndex(ElasticsearchClient esClient, String indexName) throws IOException {  
    if (existsIndex(esClient, indexName)) {  
        log.info("index: {} exists!", indexName);  
        DeleteIndexResponse deleteIndexResponse = esClient.indices().delete(s -> s.index(indexName));  
        log.info("删除索引操作结果:{}", deleteIndexResponse.acknowledged());  
    } else {  
        log.info("index: {} not found!", indexName);  
    }  
}

更新Mappings

public static void updateMappings(ElasticsearchClient esClient, String indexName, Map<String, Property> documentMap) throws IOException {  
    PutMappingRequest putMappingRequest = PutMappingRequest.of(m -> m.index(indexName).properties(documentMap));  
    PutMappingResponse putMappingResponse = esClient.indices().putMapping(putMappingRequest);  
    boolean acknowledged = putMappingResponse.acknowledged();  
    log.info("update mappings ack: {}", acknowledged);  
}

使用更新Mappings方法

@Test  
public void updateMappingsTest() throws IOException {  
    Map<String, Property> documentMap = new HashMap<>();  
    documentMap.put("name", Property.of(p -> p.text(TextProperty.of(t -> t.index(true)))));  
    documentMap.put("location", Property.of(p -> p.geoPoint(GeoPointProperty.of(g -> g.ignoreZValue(true)))));  
    // index 设置为 true,才可以使用 search range 功能  
    documentMap.put("age", Property.of(p -> p.integer(IntegerNumberProperty.of(i -> i.index(true)))));  
    EsUtils.updateMappings(esClient, indexName, documentMap);  
}

文档操作

实体类

@Data  
public class Product {  
    private String id;  
    private String name;  
    private String location;  
    private Integer age;  
    private String polygon;
}

新增

public static void addOneDocument(ElasticsearchClient esClient, String indexName, Product product) throws IOException {  
    IndexResponse indexResponse = esClient.index(i -> i.index(indexName).id(product.getId()).document(product));  
    log.info("add one document result: {}", indexResponse.result().jsonValue());  
}

批量新增

public static void batchAddDocument(ElasticsearchClient esClient, String indexName, List<Product> products) throws IOException {  
    List<BulkOperation> bulkOperations = new ArrayList<>();  
    products.forEach(p -> bulkOperations.add(BulkOperation.of(b -> b.index(c -> c.id(p.getId()).document(p)))));  
    BulkResponse bulkResponse = esClient.bulk(s -> s.index(indexName).operations(bulkOperations));  
    bulkResponse.items().forEach(b -> log.info("bulk response result = {}", b.result()));  
    log.error("bulk response.error() = {}", bulkResponse.errors());  
}

查询

public static void getDocument(ElasticsearchClient esClient, String indexName, String id) throws IOException {  
    GetResponse<Product> getResponse = esClient.get(s -> s.index(indexName).id(id), Product.class);  
    if (getResponse.found()) {  
        Product source = getResponse.source();  
        log.info("get response: {}", source);  
    }  
    // 判断文档是否存在  
    BooleanResponse booleanResponse = esClient.exists(s -> s.index(indexName).id(id));  
    log.info("文档id:{},是否存在:{}", id, booleanResponse.value());  
}

更新

public static void updateDocument(ElasticsearchClient esClient, String indexName, Product product) throws IOException {  
    UpdateResponse<Product> updateResponse = esClient.update(s -> s.index(indexName).id(product.getId()).doc(product), Product.class);  
    log.info("update doc result: {}", updateResponse.result());  
}

删除

public static void deleteDocument(ElasticsearchClient esClient, String indexName, String id) {  
    try {  
        DeleteResponse deleteResponse = esClient.delete(s -> s.index(indexName).id(id));  
        log.info("del doc result: {}", deleteResponse.result());  
    } catch (IOException e) {  
        log.error("del doc failed, error: ", e);  
    }  
}

批量删除

public static void batchDeleteDocument(ElasticsearchClient esClient, String indexName, List<String> ids) {  
    List<BulkOperation> bulkOperations = new ArrayList<>();  
    ids.forEach(a -> bulkOperations.add(BulkOperation.of(b -> b.delete(c -> c.id(a)))));  
    try {  
        BulkResponse bulkResponse = esClient.bulk(a -> a.index(indexName).operations(bulkOperations));  
        bulkResponse.items().forEach(a -> log.info("batch del result: {}", a.result()));  
        log.error("batch del bulk resp errors: {}", bulkResponse.errors());  
    } catch (IOException e) {  
        log.error("batch del doc failed, error: ", e);  
    }  
}

搜索

单个搜索

public static void searchOne(ElasticsearchClient esClient, String indexName, String searchText) throws IOException {  
    SearchResponse<Product> searchResponse = esClient.search(s -> s  
            .index(indexName)  
            // 搜索请求的查询部分(搜索请求也可以有其他组件,如聚合)  
            .query(q -> q  
                    // 在众多可用的查询变体中选择一个。我们在这里选择匹配查询(全文搜索)  
                    .match(t -> t  
                            .field("name")  
                            .query(searchText))), Product.class);  
    TotalHits total = searchResponse.hits().total();  
    boolean isExactResult = total != null && total.relation() == TotalHitsRelation.Eq;  
    if (isExactResult) {  
        log.info("search has: {} results", total.value());  
    } else {  
        log.info("search more than : {} results", total.value());  
    }  
    List<Hit<Product>> hits = searchResponse.hits().hits();  
    for (Hit<Product> hit : hits) {  
        Product source = hit.source();  
        log.info("Found result: {}", source);  
    }  
}

分页搜索

public static void searchPage(ElasticsearchClient esClient, String indexName, String searchText) throws IOException {  
    Query query = RangeQuery.of(r -> r  
                    .field("age")  
                    .gte(JsonData.of(8)))  
            ._toQuery();  
  
    SearchResponse<Product> searchResponse = esClient.search(s -> s  
                    .index(indexName)  
                    .query(q -> q  
                            .bool(b -> b.must(query)))  
                    // 分页查询,从第0页开始查询四个doc  
                    .from(0)  
                    .size(4)  
                    // 按id降序排列  
                    .sort(f -> f  
                            .field(o -> o  
                                    .field("age").order(SortOrder.Desc))),  
            Product.class);  
    List<Hit<Product>> hits = searchResponse.hits().hits();  
    for (Hit<Product> hit : hits) {  
        Product product = hit.source();  
        log.info("search page result: {}", product);  
    }  
}

参考

  1. ElasticSearch官方文档
  2. Elasticsearch Java API Client
  3. 俊逸的博客(ElasticSearchx系列)
  4. Elasticsearch Java API 客户端(中文文档)

标签:info,index,indexName,log,Java,API,esClient,基本操作,String
From: https://www.cnblogs.com/kingstar718/p/17772463.html

相关文章

  • 节点安装Java 1.8
    下载jdk-8u361-linux-x64.tar.gzhttps://www.oracle.com/java/technologies/downloads上传jdk-8u361-linux-x64.tar.gz到node1以下命令都是在node1上执行解压tar-zxvfjdk-8u361-linux-x64.tar.gz-C/export/server/配置软连接(快捷方式)ln-s/export/server/jdk1.8......
  • JsonPath使用(Java)
    JsonPath使用(Java)Java有一些类似于jq的语法库和工具。其中一个叫做JsonPath,它允许使用类似于jq的语法来查询和操作JSON数据。可以使用JsonPath来提取特定的JSON字段、过滤数据、执行计算等操作。另外,还有一些其他的Java库和框架也提供了类似的功能,比如FastJson,Gson和Jackson。这......
  • TDengine 资深研发整理:基于 SpringBoot 多语言实现 API 返回消息国际化
    作为一款在Java开发社区中广受欢迎的技术框架,SpringBoot在开发者和企业的具体实践中应用广泛。具体来说,它是一个用于构建基于Java的Web应用程序和微服务的框架,通过简化开发流程、提供约定大于配置的原则以及集成大量常用库和组件,SpringBoot能够帮助开发者更快速、更高效地......
  • Java拾贝第五天——抽象和接口
    Java拾贝不建议作为0基础学习,都是本人想到什么写什么如果父类的方法本身不需要实现,仅仅是为了定义方法。目的是让子类去重写它,那么,可以把父类的方法声明为抽象(abstract)方法classCandy{publicabstractvoidsell();}//无法通过编译若某类中拥有一个或若干个抽象方......
  • java在ubuntu上部署生产环境(适合小项目)
    一、概述需求:将SpringBoot项目打包成jar包,快速部署到云服务器的生产环境。(小型项目)二、部署步骤1.配置好项目运行所需的环境2.将jar包上传到服务器的指定目录(可以自定义)。如:/usr/local/或/tony/jar/(这是个自定义目录)3.创建一个服务文件并将其放入:/etc/system......
  • [911] Read Data from Google Sheets into Pandas without the Google Sheets API (.g
    ref:ReadDatafromGoogleSheetsintoPandaswithouttheGoogleSheetsAPIimportpandasaspdsheet_id="1XqOtPkiE_Q0dfGSoyxrH730RkwrTczcRbDeJJpqRByQ"sheet_name="Sheet1"url=f"https://docs.google.com/spreadsheets/d/{sheet......
  • java
    "循环加载"(circulardependency)指的是,a脚本的执行依赖b脚本,而b脚本的执行又依赖a脚本。 css复制代码//a.jsvarb=require('b');//b.jsvara=require('a');通常,"循环加载"表示存在强耦合,如果处理不好,还可能导致递归加载,使得程序无法执行,因此应该避免出现......
  • 【有趣的小细节】在Java中native方法hashcode()默认是如何生成哈希码的?
    之前看其他文章说,hashcode是根据对象的内存地址生成的。但为了满足自己的好奇心,同时验证这个结论是否是真实的,我半个月前深究了一下。今天突然想起来这回事了,把结论记录一下。结论目前hashcode的方式有以下六种算法:HashCodeMode==0:由操作系统生成的一个随机数。HashCodeMode==1:基......
  • Qt SQL API相关操作
    作者:苏丙榅链接:https://subingwen.cn/qt/qt-db/?highlight=sql来源:爱编程的大丙著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。另外,推荐野火关于sqlite 的文档:https://doc.embedfire.com/linux/qt/embed/zh/latest/ebf_qt/senior/qt_sqlite.html......
  • 在CMake中配置使用Intel One API的注意事项
    环境IntelOneAPI2023.2CMake3.27.7VisualStudio2022Community(withC++desktop)样例程序代码1#include<iostream>23intmain()4{5std::cout<<"Hello,CMake!"<<std::endl;6std::cin.get();7return0;8......