Elasticsearch8.x版本中RestHighLevelClient被棄用徐矩,新版本中全新的Java客戶端Elasticsearch Java API Client中常用API練習(xí)

Es的java API客戶端

在Es7.15版本之后怯屉,es官方將它的高級客戶端RestHighLevelClient標(biāo)記為棄用狀態(tài)贼陶。同時推出了全新的java API客戶端Elasticsearch Java API Client,該客戶端也將在Elasticsearch8.0及以后版本中成為官方推薦使用的客戶端孩灯。

Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API闺金。且支持所有API數(shù)據(jù)類型,并且不再有原始JSON Value屬性峰档。它是針對Elasticsearch8.0及之后版本的客戶端败匹。

感興趣的小伙伴可以去官方文檔看看:Elasticsearch官網(wǎng)8.x版本下Java客戶端文檔---Elasticsearch Java API Client使用

新建maven項(xiàng)目

maven中引入依賴坐標(biāo)

        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.1.0</version>
        </dependency>
         <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

創(chuàng)建連接

    @Test
    public void create() throws IOException {
        // 創(chuàng)建低級客戶端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)
        ).build();
        // 使用Jackson映射器創(chuàng)建傳輸層
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        // 創(chuàng)建API客戶端
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 關(guān)閉ES客戶端
        transport.close();
        restClient.close();
    }

索引index的基本語法

創(chuàng)建索引

    @Test
    public void create() throws IOException {
        // 創(chuàng)建低級客戶端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)
        ).build();
        // 使用Jackson映射器創(chuàng)建傳輸層
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        // 創(chuàng)建API客戶端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 創(chuàng)建索引
        CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
        // 響應(yīng)狀態(tài)
        Boolean acknowledged = createIndexResponse.acknowledged();
        System.out.println("索引操作 = " + acknowledged);

        // 關(guān)閉ES客戶端
        transport.close();
        restClient.close();
    }

查詢索引

    @Test
    public void query() throws IOException {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost",9200)
        ).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 查詢索引
        GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));
        System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
        System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());

        transport.close();
        restClient.close();
    }

\color{red}{注:如果查詢的index不存在會在控制臺拋出index_not_found_exception.}

刪除索引

    @Test
    public void delete() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 刪除索引
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));
        System.out.println("刪除操作 = " + deleteIndexResponse.acknowledged());

        transport.close();
        restClient.close();
    }

文檔document的操作

創(chuàng)建User對象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private String sex;
    private Integer age;
}

添加document

    @Test
    public void addDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 向user對象中添加數(shù)據(jù)
        User user = new User("java客戶端", "男", 18);
        // 向索引中添加數(shù)據(jù)
        CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));
        System.out.println("createResponse.result() = " + createResponse.result());

        transport.close();
        restClient.close();
    }

$\color{red}{注:index中參數(shù)為文檔所屬的索引名,id中參數(shù)為當(dāng)文檔的id讥巡,document為文檔數(shù)據(jù)掀亩,新版本支持直接傳入java對象.} $  

查詢document

    @Test
    public void queryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 構(gòu)建請求
        GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);
        System.out.println("getResponse.source().toString() = " + getResponse.source().toString());

        transport.close();
        restClient.close();
    }

\color{red}{注:如果查不到控制臺拋出NullPointerException.}

修改document

    @Test
    public void modifyDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 使用map集合封裝需要修改的內(nèi)容
        Map<String, Object> map = new HashMap<>();
        map.put("name", "java客戶端aaa");
        // 構(gòu)建請求
        UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);
        System.out.println("updateResponse.result() = " + updateResponse.result());

        transport.close();
        restClient.close();
    }

刪除document

    @Test
    public void removeDocument() throws  IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 構(gòu)建請求
        DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));
        System.out.println("deleteResponse.result() = " + deleteResponse.result());

        transport.close();
        restClient.close();
    }

批量添加document

    @Test
    public void batchAddDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 構(gòu)建一個批量數(shù)據(jù)集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
        // 調(diào)用bulk方法執(zhí)行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }

\color{red}{批量添加的核心是需要構(gòu)建一個泛型為BulkOperation的ArrayList集合,實(shí)質(zhì)上是將多個請求包裝到一個集合中欢顷,進(jìn)行統(tǒng)一請求槽棍,進(jìn)行構(gòu)建請求時調(diào)用bulk方法,實(shí)現(xiàn)批量添加效果 .}

批量刪除

    @Test
    public void batchDeleteDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 構(gòu)建一個批量數(shù)據(jù)集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1003").index("user_test")).build());
        // 調(diào)用bulk方法執(zhí)行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }

全量查詢

    @Test
    public void queryAllDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 全量查詢
        SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);
        HitsMetadata<User> hits = searchResponse.hits();
        for (Hit<User> hit : hits.hits()) {
            System.out.println("user = " + hit.source().toString());
        }
        System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());

        transport.close();
        restClient.close();
    }

分頁查詢

    @Test
    public void pagingQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 分頁查詢
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .query(q -> q.matchAll(m -> m))
                        .from(2)
                        .size(2)
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

\color{red}{分頁查詢就是在全量查詢的基礎(chǔ)上增加了從第幾條開始抬驴,每頁顯示幾條 .}

排序查詢

    @Test
    public void sortQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 排序查詢
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .query(q -> q.matchAll(m -> m))
                        .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

條件查詢

    @Test
    public void conditionQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 條件查詢
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.matchAll(m -> m))
                        .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                        .source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

\color{red}{includes是顯示的字段刹泄,excludes是排除的字段.}

組合查詢

    @Test
    public void combinationQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 組合查詢
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .must(m -> m.match(u -> u.field("age").query(21)))
                        .must(m -> m.match(u -> u.field("sex").query("男")))
                        .mustNot(m -> m.match(u -> u.field("sex").query("女")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

    @Test
    public void combinationQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 組合查詢
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .should(h -> h.match(u -> u.field("age").query(19)))
                        .should(h -> h.match(u -> u.field("sex").query("男")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

must是必須滿足所有條件,should只要滿足一個就行

范圍查詢

    @Test
    public void scopeQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 范圍查詢怎爵,gte()表示取大于等于特石,gt()表示大于,lte()表示小于等于
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .range(r -> r.field("age").gte(JsonData.of(20)).lt(JsonData.of(21))))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

模糊查詢

    @Test
    public void fuzzyQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 模糊查詢鳖链,fuzziness表示差幾個可以查詢出來
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .fuzzy(f -> f.field("name").value("tst").fuzziness("2")))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

高亮查詢

    @Test
    public void highlightQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 高亮查詢
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .term(t -> t.field("name").value("test3")))
                        .highlight(h -> h.fields("name", f -> f.preTags("<font color='red'>").postTags("</font>")))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

聚合查詢

    @Test
    public void aggregateQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 聚合查詢姆蘸,取最大年齡
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").aggregations("maxAge", a ->a.max(m -> m.field("age")))
                , User.class);
        searchResponse.aggregations().entrySet().forEach(f -> System.out.println(f.getKey() + ":" + f.getValue().max().value()));

        transport.close();
        restClient.close();
    }

分組查詢

    @Test
    public void groupQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 分組查詢
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test")
                        .aggregations("ageGroup", a ->a.terms(t -> t.field("age")))
                , User.class);
        searchResponse.aggregations().get("ageGroup").lterms().buckets().array().forEach(f -> System.out.println(f.key() + ":" + f.docCount()));

        transport.close();
        restClient.close();
    }

\color{red}{分組查詢實(shí)質(zhì)上是聚合查詢的一種.}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末墩莫,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子逞敷,更是在濱河造成了極大的恐慌狂秦,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件推捐,死亡現(xiàn)場離奇詭異裂问,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)牛柒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門堪簿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人皮壁,你說我怎么就攤上這事椭更。” “怎么了蛾魄?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵虑瀑,是天一觀的道長。 經(jīng)常有香客問我滴须,道長舌狗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任扔水,我火速辦了婚禮把夸,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铭污。我一直安慰自己恋日,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布嘹狞。 她就那樣靜靜地躺著岂膳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪磅网。 梳的紋絲不亂的頭發(fā)上谈截,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天,我揣著相機(jī)與錄音涧偷,去河邊找鬼簸喂。 笑死,一個胖子當(dāng)著我的面吹牛燎潮,可吹牛的內(nèi)容都是我干的喻鳄。 我是一名探鬼主播,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼确封,長吁一口氣:“原來是場噩夢啊……” “哼除呵!你這毒婦竟也來了再菊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤颜曾,失蹤者是張志新(化名)和其女友劉穎纠拔,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體泛豪,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡稠诲,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了诡曙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片臀叙。...
    茶點(diǎn)故事閱讀 38,039評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖岗仑,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情聚请,我是刑警寧澤荠雕,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站驶赏,受9級特大地震影響炸卑,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜煤傍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一盖文、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蚯姆,春花似錦五续、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至郭毕,卻和暖如春它碎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背显押。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工扳肛, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人乘碑。 一個月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓挖息,卻偏偏與公主長得像,于是被迫代替她去往敵國和親兽肤。 傳聞我的和親對象是個殘疾皇子旋讹,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評論 2 345

推薦閱讀更多精彩內(nèi)容