ElasticSearch Java API 基本操作

这篇具有很好参考价值的文章主要介绍了ElasticSearch Java API 基本操作。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

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

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

代码示例已上传github。文章来源地址https://www.toymoban.com/news/detail-710950.html

版本

  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 客户端(中文文档)

到了这里,关于ElasticSearch Java API 基本操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ElasticSearch 中的中文分词器以及索引基本操作详解,Java高并发编程详解深入理解pdf

    PUT book/_settings { “number_of_replicas”: 2 } 修改成功后,如下: 更新分片数也是一样。 2.3 修改索引的读写权限 索引创建成功后,可以向索引中写入文档: PUT book/_doc/1 { “title”:“三国演义” } 写入成功后,可以在 head 插件中查看: 默认情况下,索引是具备读写权限的,当然这

    2024年04月09日
    浏览(37)
  • Elasticsearch基本操作之文档操作

    本文来说下Elasticsearch基本操作之文档操作 文档概述 在创建好索引的基础上来创建文档,并添加数据。 这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式。 在 apifox 中,向 ES 服务器发 POST 请求 :http://localhost:9200/person/_doc,请求体内容为: 服务器响

    2024年02月01日
    浏览(29)
  • ElasticSearch - 基本操作

    本文记录 ES 的一些基本操作,就是对官方文档的一些整理,按自己的习惯重新排版,凑合着看。官方的更详细,建议看官方的。 下文以 books 为索引名举例。 添加单个文档 (没有索引会自动创建) 不指定 id,会随机生成,如果需要指定 id,使用 POST books/_doc/id 还可以使用 put 的

    2024年03月20日
    浏览(27)
  • ElasticSearch8 - 基本操作

    本文记录 ES 的一些基本操作,就是对官方文档的一些整理,按自己的习惯重新排版,凑合着看。官方的更详细,建议看官方的。 下文以 books 为索引名举例。 添加单个文档 (没有索引会自动创建) 不指定 id,会随机生成,如果需要指定 id,使用 POST books/_doc/id 还可以使用 put 的

    2024年04月09日
    浏览(27)
  • Elasticsearch的基本操作与管理

    Elasticsearch是一个基于分布式搜索和分析引擎,由Netflix开发,后被Elasticsearch公司继承。它是一个实时、可扩展、高性能的搜索引擎,可以处理大量数据并提供快速、准确的搜索结果。Elasticsearch使用Lucene库作为底层搜索引擎,并提供RESTful API和JSON格式进行数据交互。 Elasticsea

    2024年02月20日
    浏览(22)
  • elasticsearch基本操作之--QueryBuilders

    使用QueryBuilders进行范围时间组合查询 es存储日志 是按照UTC时间格式存放,以@timestamp 作为时间范围查询条件,即from(Date1) to(Date2)Date1、Date2入参必须是标准的utc格式; 数字

    2024年02月13日
    浏览(34)
  • Elasticsearch(四)——ES基本操作

    一、Rest风格说明( 非常重要 ) Rest风格一种软件架构风格,而不是标准,只是提供了一组设计原则和约束条件。 它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 基于Rest命令说明 method url地址 描述 PUT localh

    2024年02月02日
    浏览(27)
  • 超详细讲解Elasticsearch的基本操作

    📢📢📢📣📣📣 哈喽!大家好 ,我是【 一心同学 】,一位上进心十足的【 Java领域博主】! 😜😜😜 ✨【 一心同学 】的 写作风格 :喜欢用【 通俗易懂 】的文笔去讲解每一个知识点,而不喜欢用【 高大上 】的官方陈述。 ✨【 一心同学 】博客的 领域 是【 面向后端技

    2024年02月03日
    浏览(32)
  • ElasticSearch 8.11 基本操作练习

    ES 8.0 默认把type给去掉了 新增/编辑 PUT /index/id  幂等操作 必须指定id 同一个id为修改 POST /index/id 非幂等操作 指定id时和put操作一样 不指定id 每次都会新增 id为系统随机分配 删除 DELETE /index  删除整个索引 DELETE /index/_doc/id  删除指定document  查询  GET /index/_search  不带条件查

    2024年02月04日
    浏览(28)
  • Elasticsearch 7.x 基本操作 (CRUD)

    Elasticsearch 是一个流行的开源搜索引擎,用于存储、搜索和分析数据。下面是 Elasticsearch 7.x 版本的基本操作(CRUD): 1、创建索引: 2、查看索引: 3、删除索引: 4、创建文档: 5、获取文档: 6、更新文档: 7、删除文档: 这些操作可以通过 Elasticsearch 的 REST API 进行。注意

    2024年02月15日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包