国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

ElasticSearch Java API 基本操作

這篇具有很好參考價值的文章主要介紹了ElasticSearch Java API 基本操作。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言

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

本文主要參考了相關(guān)博文,自己手動編寫了下相關(guān)操作代碼,包括更新mappings等操作的java代碼。

代碼示例已上傳github。文章來源地址http://www.zghlxwxcb.cn/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;  
}

索引

創(chuàng)建索引

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("刪除索引操作結(jié)果:{}", 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 設(shè)置為 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 客戶端(中文文檔)

到了這里,關(guān)于ElasticSearch Java API 基本操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • ElasticSearch 中的中文分詞器以及索引基本操作詳解,Java高并發(fā)編程詳解深入理解pdf

    ElasticSearch 中的中文分詞器以及索引基本操作詳解,Java高并發(fā)編程詳解深入理解pdf

    PUT book/_settings { “number_of_replicas”: 2 } 修改成功后,如下: 更新分片數(shù)也是一樣。 2.3 修改索引的讀寫權(quán)限 索引創(chuàng)建成功后,可以向索引中寫入文檔: PUT book/_doc/1 { “title”:“三國演義” } 寫入成功后,可以在 head 插件中查看: 默認情況下,索引是具備讀寫權(quán)限的,當(dāng)然這

    2024年04月09日
    瀏覽(26)
  • Elasticsearch基本操作之文檔操作

    Elasticsearch基本操作之文檔操作

    本文來說下Elasticsearch基本操作之文檔操作 文檔概述 在創(chuàng)建好索引的基礎(chǔ)上來創(chuàng)建文檔,并添加數(shù)據(jù)。 這里的文檔可以類比為關(guān)系型數(shù)據(jù)庫中的表數(shù)據(jù),添加的數(shù)據(jù)格式為 JSON 格式。 在 apifox 中,向 ES 服務(wù)器發(fā) POST 請求 :http://localhost:9200/person/_doc,請求體內(nèi)容為: 服務(wù)器響

    2024年02月01日
    瀏覽(21)
  • ElasticSearch - 基本操作

    ElasticSearch - 基本操作

    本文記錄 ES 的一些基本操作,就是對官方文檔的一些整理,按自己的習(xí)慣重新排版,湊合著看。官方的更詳細,建議看官方的。 下文以 books 為索引名舉例。 添加單個文檔 (沒有索引會自動創(chuàng)建) 不指定 id,會隨機生成,如果需要指定 id,使用 POST books/_doc/id 還可以使用 put 的

    2024年03月20日
    瀏覽(26)
  • ElasticSearch8 - 基本操作

    ElasticSearch8 - 基本操作

    本文記錄 ES 的一些基本操作,就是對官方文檔的一些整理,按自己的習(xí)慣重新排版,湊合著看。官方的更詳細,建議看官方的。 下文以 books 為索引名舉例。 添加單個文檔 (沒有索引會自動創(chuàng)建) 不指定 id,會隨機生成,如果需要指定 id,使用 POST books/_doc/id 還可以使用 put 的

    2024年04月09日
    瀏覽(26)
  • Elasticsearch(四)——ES基本操作

    Elasticsearch(四)——ES基本操作

    一、Rest風(fēng)格說明( 非常重要 ) Rest風(fēng)格一種軟件架構(gòu)風(fēng)格,而不是標(biāo)準(zhǔn),只是提供了一組設(shè)計原則和約束條件。 它主要用于客戶端和服務(wù)器交互類的軟件。基于這個風(fēng)格設(shè)計的軟件可以更簡潔,更有層次,更易于實現(xiàn)緩存等機制。 基于Rest命令說明 method url地址 描述 PUT localh

    2024年02月02日
    瀏覽(59)
  • elasticsearch基本操作之--QueryBuilders

    elasticsearch基本操作之--QueryBuilders

    使用QueryBuilders進行范圍時間組合查詢 es存儲日志 是按照UTC時間格式存放,以@timestamp 作為時間范圍查詢條件,即from(Date1) to(Date2)Date1、Date2入?yún)⒈仨毷菢?biāo)準(zhǔn)的utc格式; 數(shù)字

    2024年02月13日
    瀏覽(13)
  • Elasticsearch的基本操作與管理

    Elasticsearch是一個基于分布式搜索和分析引擎,由Netflix開發(fā),后被Elasticsearch公司繼承。它是一個實時、可擴展、高性能的搜索引擎,可以處理大量數(shù)據(jù)并提供快速、準(zhǔn)確的搜索結(jié)果。Elasticsearch使用Lucene庫作為底層搜索引擎,并提供RESTful API和JSON格式進行數(shù)據(jù)交互。 Elasticsea

    2024年02月20日
    瀏覽(22)
  • ElasticSearch 8.11 基本操作練習(xí)

    ES 8.0 默認把type給去掉了 新增/編輯 PUT /index/id? 冪等操作 必須指定id 同一個id為修改 POST /index/id 非冪等操作 指定id時和put操作一樣 不指定id 每次都會新增 id為系統(tǒng)隨機分配 刪除 DELETE /index? 刪除整個索引 DELETE /index/_doc/id? 刪除指定document? 查詢? GET /index/_search? 不帶條件查

    2024年02月04日
    瀏覽(17)
  • 超詳細講解Elasticsearch的基本操作

    超詳細講解Elasticsearch的基本操作

    ???????????? 哈嘍!大家好 ,我是【 一心同學(xué) 】,一位上進心十足的【 Java領(lǐng)域博主】! ?????? ?【 一心同學(xué) 】的 寫作風(fēng)格 :喜歡用【 通俗易懂 】的文筆去講解每一個知識點,而不喜歡用【 高大上 】的官方陳述。 ?【 一心同學(xué) 】博客的 領(lǐng)域 是【 面向后端技

    2024年02月03日
    瀏覽(47)
  • Elasticsearch 實戰(zhàn)之三:ES 基本操作

    Elasticsearch 實戰(zhàn)之三:ES 基本操作

    目錄 0. 數(shù)據(jù)格式說明 1. ES的基本操作 1.1?索引操作 1.1.1?建立索引 1.1.2? 刪除索引 1.1.3??查詢索引 1.2 映射操作 1.2.1 建立映射 1.2.2 查詢映射 1.3 基本操作-CRUD 1.3.1 新增和替換文檔 1.3.2 查詢文檔 在實戰(zhàn)開始之前,為了便于書寫和溝通,本文先來約定一下如何在文章中表達請求

    2024年02月11日
    瀏覽(20)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包