Elasticsearch基本的Java Api 增刪查改操作

1概述

最近在學習ES做了如下整理,這裏安裝就不說了,百度都有.這篇文章先介紹創建maven項目使用java api操作ES,後面會使用SpringBoot去集成ES,簡單說下ES到底是什麼?
Elasticsearc是基於lucene實現,隱藏複雜性,提供了簡單易用的restful-api接口 java api接口(還有其他語言)
它是一個實時分佈式搜索引擎.它用於全文搜素,結構化對比和分析.

我們還要知道它的基本術語:

  1. Index(索引-數據庫)
    索引包含一堆有相似結構的文檔數據,比如可以有一個客戶索引,商品分類索引,訂單索引,索引有一個名稱。一個index包含很多document,一個index就代表了一類類似的或者相同的document。比如說建立一個product index,商品索引,裏面可能就存放了所有的商品數據,所有的商品document。
  2. Type(類型-表)
    每個索引裏都可以有一個或多個type,type是index中的一個邏輯數據分類,一個type下的document,都有相同的field,比如博客系統,有一個索引,可以定義用戶數據type,博客數據type,評論數據type。
    商品index,裏面存放了所有的商品數據,商品document
    但是商品分很多種類,每個種類的document的field可能不太一樣,比如說電器商品,可能還包含一些諸如售後時間範圍這樣的特殊field;生鮮商品,還包含一些諸如生鮮保質期之類的特殊field
  3. Document(文檔-行)
    文檔是es中的最小數據單元,一個document可以是一條客戶數據,一條商品分類數據,一條訂單數據,通常用JSON數據結構表示,每個index下的type中,都可以去存儲多個document。
  4. Field(字段-列)
    Field是Elasticsearch的最小單位。一個document裏面有多個field,每個field就是一個數據字段。

知道這些我們就可以去做一些簡單的操作了.
但是在操作之前我們還是把官網貼出來方便學習:
官網
java api
github地址
看完這些絕對夠了.哈哈

2 環境

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

      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.2.2</version>
      </dependency>

      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.0</version>
      </dependency>

3 基本操作

package cn.zhangyu.util;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ElasticSearchClient {

    public  PreBuiltTransportClient getClient() {
        Settings settings = Settings.builder().put("cluster.name","my-application").build();

        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        try {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.13.82.17"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return client;
    }
}


package cn.zhangyu;


import cn.zhangyu.util.ElasticSearchClient;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class ElasticSearchApp {

    ElasticSearchClient elasticSearchClient = new ElasticSearchClient();

    //創建索引
    @Test
    public void createIndex() {
        elasticSearchClient.getClient().admin().indices().prepareCreate("blog2").get();
        elasticSearchClient.getClient().close();
    }

    //刪除索引
    public void delIndex(){
        elasticSearchClient.getClient().admin().indices().prepareDelete("blog2").get();
        elasticSearchClient.getClient().close();
    }

    //新建文檔  源數據爲json字符串
    @Test
    public void createDocumentByJson(){
        //1 準備文檔數據
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基於Lucene的搜索服務器\","
                + "\"content\":\"它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口\"" + "}";
        //2 創建文檔
        IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "1")
                .setSource(json).execute().actionGet();

        //3 結果
        System.out.println("index:" + response.getIndex());
        System.out.println("type:" + response.getType());
        System.out.println("String:" + response.toString());

        //4 關閉連接
        elasticSearchClient.getClient().close();
    }

    //新建文檔(源數據map方式添加json)
    @Test
    public void createDocumentByMap(){
        //1 準備數據源
        Map<String,Object>  json = new HashMap<>();
        json.put("id","2");
        json.put("title","基於Lucen的搜索服務器");
        json.put("content","它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口");

        //2 創建文檔
        IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "2")
                .setSource(json).execute().actionGet();

        //3 打印返回的結果
        System.out.println("index:" + response.getIndex());
        System.out.println("type:" + response.getType());
        System.out.println("id:" + response.getId());
        System.out.println("version:" + response.getVersion());
        System.out.println("result:" + response.getResult());

        //4 關閉連接
        elasticSearchClient.getClient().close();

    }

    //新建文檔(源數據es構建器添加json)
    @Test
    public void createIndexByEs() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
                .field("id", "3")
                .field("title", "基於Lucene的搜索服務器")
                .field("content", "它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口。")
                .endObject();

        IndexResponse indexResponse = elasticSearchClient.getClient().prepareIndex("blog", "article", "3")
                .setSource(builder).execute().actionGet();

        //3 打印結果
        System.out.println("index:" + indexResponse.getIndex());
        System.out.println("type:" + indexResponse.getType());
        System.out.println("id:" + indexResponse.getId());
        System.out.println("version:" + indexResponse.getVersion());
        System.out.println("result:" + indexResponse.getResult());

        //4 關閉連接
        elasticSearchClient.getClient().close();
    }

    //搜索數據(單索引)
    @Test
    public void getData(){
        //1 查詢文檔
        GetResponse response = elasticSearchClient.getClient()
                .prepareGet("blog","article","1")
                .get();

        //2 打印結果
        System.out.println(response.getSourceAsString());
        //3 關閉連接
        elasticSearchClient.getClient().close();
    }

    //搜索數據(多索引)
    @Test
    public void getMultiData(){
           //1 查詢多個文檔
        MultiGetResponse responses = elasticSearchClient.getClient().prepareMultiGet()
        //這裏可以傳遞可變參數,即多個參數    (參考源碼)
                .add("blog", "article", "1","2","3","4","5")
//                .add("blog", "article", "2")
//                .add("blog", "article", "3")
//                .add("blog", "article", "5")
                .get();

        //2 遍歷結果 lambda表達式
        responses.forEach(itemResponses -> System.out.println(itemResponses.getResponse().getSourceAsString()));

        //3 關閉連接
        elasticSearchClient.getClient().close();
    }

    //更新文檔數據
    @Test
    public void updateData() throws IOException, ExecutionException, InterruptedException {
        // 創建更新數據的請求對象
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("blog");
        updateRequest.type("article");
        updateRequest.id("3");

        //會對沒有的字段添加,已有的字段替換
        updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                     .field("title", "基於Lucene的搜索服務器")
                     .field("content",
                                "它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口。大數據前景無限")
                     .field("createDate", "2017-8-22").endObject());

        //獲取更新後的值
        UpdateResponse updateResponse = elasticSearchClient.getClient().update(updateRequest).get();

        //3 打印結果
        System.out.println("index:" + updateResponse.getIndex());
        System.out.println("type:" + updateResponse.getType());
        System.out.println("id:" + updateResponse.getId());
        System.out.println("version:" + updateResponse.getVersion());
        System.out.println("result:" + updateResponse.getResult());

        //4 關閉連接
        elasticSearchClient.getClient().close();
    }

    //更新文檔數據(upsert)
    @Test
    public void upsertData() throws Exception{
        // 設置查詢條件, 查找不到則添加
        IndexRequest indexRequest = new IndexRequest("blog", "article", "4");
        indexRequest.source(XContentFactory.jsonBuilder().startObject()
                .field("title", "搜索服務器")
                .field("content","它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口。Elasticsearch是用Java開發的,並作爲Apache許可條款下的開放源碼發佈,是當前流行的企業級搜索引擎。設計用於雲計算中,能夠達到實時搜索,穩定,可靠,快速,安裝使用方便。")
                .endObject());

        //設置更新,查找更新下面的設置
        UpdateRequest updateRequest = new UpdateRequest("blog", "article", "4");
        updateRequest.doc(XContentFactory.jsonBuilder().startObject()
                .field("user","張3").endObject()).upsert(indexRequest);

        elasticSearchClient.getClient().update(updateRequest).get();
        //4 關閉連接
        elasticSearchClient.getClient().close();

    }

    //刪除文檔數據
    @Test
    public void delData(){
        //1 刪除文檔
        DeleteResponse deleteResponse = elasticSearchClient.getClient().prepareDelete("blog", "article", "4").get();

        // 2 打印返回的結果
        System.out.println("index:" + deleteResponse.getIndex());
        System.out.println("type:" + deleteResponse.getType());
        System.out.println("id:" + deleteResponse.getId());
        System.out.println("version:" + deleteResponse.getVersion());
        System.out.println("found:" + deleteResponse.getResult());

    }
}

 //查詢所有
    @Test
    public void matchAllQuery(){
        //1 執行查詢
        SearchResponse searchResponse = elasticSearchClient.getClient().prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery()).get();

        // 2 打印結果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 條");

        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 3 關閉連接
        elasticSearchClient.getClient().close();
    }

    //對所有字段分詞查詢
    @Test
    public void queryStringQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery(" lucene")).get();

        // 2 打印結果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 條");

        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 3 關閉連接
        elasticSearchClient.getClient().close();
    }

    /*通配符查詢

      *:表示多個字符(任意的字符)
      ?:表示單個字符

     *
     */
    @Test
    public void wildcardQuery(){
        //通配符查詢
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();

        //打印查詢結果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 條");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        //關閉連接
        elasticSearchClient.getClient().close();

    }

    //詞條查詢
    @Test
    public void termQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.termQuery("content","它")).get();

        //打印查詢結果
        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 條");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
        //關閉連接
        elasticSearchClient.getClient().close();
    }

    //模糊查詢
    @Test
    public void fuzzyQuery(){
        SearchResponse searchResponse = elasticSearchClient.getClient()
                .prepareSearch("blog").setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("title","lucene")).get();

        SearchHits hits = searchResponse.getHits();
        System.out.println("count :" + hits.getTotalHits() +" 條");
        hits.forEach(hit -> System.out.println(hit.getSourceAsString()));

        elasticSearchClient.getClient().close();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章