Java原生操作Elasticsearch

這裏Elasticsearch是單節點,版本爲5.2.2。

【1】獲取PreBuiltTransportClient

實例代碼

 	@Test
    public void getClient() throws Exception {
        Settings settings= Settings.builder().put("cluster.name","my-application").build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        byte[] addr = {(byte) 192, (byte) 168,18, (byte) 128};
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByAddress(addr),9300));
        System.out.println(client);
    }

控制檯打印

 io.netty.channel.DefaultChannelId - -Dio.netty.machineId: 28:d2:44:ff:fe:f0:2f:30 (auto-detected)
 io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024
 io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096
 io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
 io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.targetRecords: 4
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 8
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 8
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 11
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 16777216
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.tinyCacheSize: 512
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
 io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.useCacheForAllThreads: true
 io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled
 io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 0
 io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
 io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.bytebuf.checkAccessible: true
 io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@5f5b5ca4
 io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 4096
 io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2
 io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16
 io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
 org.elasticsearch.transport.netty4.Netty4Transport - connected to node [{#transport#-1}{DX4Qcrb4QAaGAgDUb-XYxg}{192.168.18.128}{192.168.18.128:9300}]
 org.elasticsearch.transport.netty4.Netty4Transport - connected to node [{node-1}{rBJNxRw2RxisNp-uBs8o4g}{10h3v06bR4SI4x4ee0F1HQ}{192.168.18.128}{192.168.18.128:9300}]
org.elasticsearch.transport.client.PreBuiltTransportClient@7af1cd63

在這裏插入圖片描述


【2】創建索引

實例代碼:

 	@Test
    public void createIndex(){
        CreateIndexResponse blog = client.admin().indices().prepareCreate("my-blog").get();
        System.out.println(blog);
        client.close();
    }

控制檯打印
在這裏插入圖片描述
查看當前ES中索引

http://192.168.18.128:9200/_cat/indices

在這裏插入圖片描述

查看my-blog詳細

http://192.168.18.128:9200/my-blog?pretty

在這裏插入圖片描述
如果不加pretty參數則如下所示:
在這裏插入圖片描述
Elasticsearch索引結束時將得到5個分片及其各自1個副本。簡單來說,操作結束時,將有10個Lucene索引分佈在集羣中。


【3】刪除索引

實例代碼

	@Test
    public void deleteIndex(){
        // 1 刪除索引
        DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete("my-blog").get();
        System.out.println(deleteIndexResponse);
        // 2 關閉連接
        client.close();
    }

控制檯打印
在這裏插入圖片描述
查詢索引確認索引已經刪除
在這裏插入圖片描述


【4】創建文檔

① 以json串方式新建文檔

當直接在ElasticSearch建立文檔對象時,如果索引不存在的,默認會自動創建,映射採用默認方式。

實例代碼:

	@Test
    public void createIndexByJson() {

        // 1 文檔數據準備
        String json = "{" + "\"id\":\"1\"," + "\"title\":\"基於Lucene的搜索服務器\","
                + "\"content\":\"它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口\"" + "}";

        // 2 創建文檔
        IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "1").setSource(json).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 關閉連接
        client.close();
    }

控制檯打印:
在這裏插入圖片描述
瀏覽器查看http://192.168.18.128:9200/my-blog?pretty
在這裏插入圖片描述


② 源數據map方式添加json創建文檔

實例代碼:

	 @Test
    public void createIndexByMap() {

        // 1 文檔數據準備
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("id", "2");
        json.put("title", "基於Lucene的搜索服務器");
        json.put("content", "它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口");

        // 2 創建文檔
        IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "2").setSource(json).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 關閉連接
        client.close();
    }

控制檯打印:
在這裏插入圖片描述
瀏覽器確認該索引文檔http://192.168.18.128:9200/my-blog/_search?pretty
在這裏插入圖片描述
瀏覽器查詢ES所有信息http://192.168.18.128:9200/_all/_search?pretty
在這裏插入圖片描述


③ 源數據es構建器添加json創建文檔

實例代碼:

	@Test
	public void createIndex() throws Exception {

		// 1 通過es自帶的幫助類,構建json數據
		XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("id", 3)
				.field("title", "基於Lucene的搜索服務器").field("content", "它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口。")
				.endObject();

		// 2 創建文檔
		IndexResponse indexResponse = client.prepareIndex("my-blog", "article", "3").setSource(builder).get();

		// 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 關閉連接
		client.close();
	}

控制檯打印:
在這裏插入圖片描述
瀏覽器查詢確認http://192.168.18.128:9200/my-blog/_search?pretty
在這裏插入圖片描述


【5】查詢索引中文檔數據

① 根據索引ID查詢單條數據

實例代碼:

	 @Test
    public void getData() throws Exception {

        // 1 查詢文檔
        GetResponse response = client.prepareGet("my-blog", "article", "1").get();

        // 2 打印搜索的結果
        System.out.println(response.getSourceAsString());

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

控制檯打印:
在這裏插入圖片描述


② 根據索引ID查詢多條數據

實例代碼:

	 @Test
    public void getMultiData() {

        // 1 查詢多個文檔
        MultiGetResponse response = client.prepareMultiGet().add("my-blog", "article", "1").add("my-blog", "article", "2", "3")
                .add("my-blog", "article", "2").get();

        // 2 遍歷返回的結果
        for(MultiGetItemResponse itemResponse:response){
            GetResponse getResponse = itemResponse.getResponse();

            // 如果獲取到查詢結果
            if (getResponse.isExists()) {
                String sourceAsString = getResponse.getSourceAsString();
                System.out.println(sourceAsString);
            }
        }

        // 3 關閉資源
        client.close();
    }

控制檯打印:
在這裏插入圖片描述


【6】更新索引文檔數據

① update-更新文檔數據

實例代碼:

 	@Test
    public void updateData() throws Throwable {

        // 1 創建更新數據的請求對象
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("my-blog");
        updateRequest.type("article");
        updateRequest.id("3");

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

        // 2 獲取更新後的值
        UpdateResponse indexResponse = client.update(updateRequest).get();

        // 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("create:" + indexResponse.getResult());

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

控制檯打印:
在這裏插入圖片描述
瀏覽器查詢確認http://192.168.18.128:9200/my-blog/_search?pretty
在這裏插入圖片描述


② upsert-更新文檔數據

設置查詢條件, 查找不到則添加IndexRequest內容,查找到則按照UpdateRequest更新。

實例代碼:

   	@Test
    public void testUpsert() throws Exception {

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

        // 設置更新, 查找到更新下面的設置
        UpdateRequest upsert = new UpdateRequest("my-blog", "article", "5")
                .doc(XContentFactory.jsonBuilder().startObject().field("user", "李四").endObject()).upsert(indexRequest);

        client.update(upsert).get();
        client.close();
    }

瀏覽器查詢確認http://192.168.18.128:9200/my-blog/_search?pretty
在這裏插入圖片描述


【7】刪除文檔數據

實例代碼:

	@Test
	public void deleteData() {
		
		// 1 刪除文檔數據
		DeleteResponse indexResponse = client.prepareDelete("blog", "article", "5").get();

		// 2 打印返回的結果
		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("found:" + indexResponse.getResult());

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

控制檯打印:
在這裏插入圖片描述
瀏覽器查詢確認http://192.168.18.128:9200/my-blog/_search?pretty
在這裏插入圖片描述


【8】條件查詢

① 查詢索引所有文檔數據(matchAllQuery)

實例代碼:

	@Test
    public void matchAllQuery() {

        // 1 執行查詢
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery()).get();

        // 2 打印查詢結果
        SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
        System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

        Iterator<SearchHit> iterator = hits.iterator();

        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每個查詢對象

            System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
        }
        // 3 關閉連接
        client.close();
    }

控制檯打印:
在這裏插入圖片描述


② 對所有字段分詞查詢(queryStringQuery)

實例代碼:

 	@Test
    public void query() {
        // 1 條件查詢
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("全文")).get();

        // 2 打印查詢結果
        SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
        System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

        Iterator<SearchHit> iterator = hits.iterator();

        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每個查詢對象

            System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
        }

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

控制檯打印:
在這裏插入圖片描述


③ 通配符查詢(wildcardQuery)

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

實例代碼:

	 @Test
    public void wildcardQuery() {

        // 1 通配符查詢
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();

        // 2 打印查詢結果
        SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
        System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

        Iterator<SearchHit> iterator = hits.iterator();

        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每個查詢對象

            System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
        }

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

控制檯打印:
在這裏插入圖片描述

在這裏插入圖片描述


④ 詞條查詢(TermQuery)

實例代碼;

 	@Test
    public void termQuery() {

        // 1 第一field查詢
//        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
//                .setQuery(QueryBuilders.termQuery("content", "全文")).get();//0條

        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.termQuery("content", "全")).get();//3條

        // 2 打印查詢結果
        SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
        System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

        Iterator<SearchHit> iterator = hits.iterator();

        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每個查詢對象

            System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
        }

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

這裏需要說明,默認詞條查詢是將每個字作爲索引進行查找,使用詞(比如全文)進行查找是找不到的。單一使用有點雞肋,需要藉助分詞器組合使用。

在這裏插入圖片描述


⑤ 模糊查詢(fuzzy)

實例代碼:

	 @Test
    public void fuzzy() {

        // 1 模糊查詢
        SearchResponse searchResponse = client.prepareSearch("my-blog").setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("content", "大")).get();

        // 2 打印查詢結果
        SearchHits hits = searchResponse.getHits(); // 獲取命中次數,查詢結果有多少對象
        System.out.println("查詢結果有:" + hits.getTotalHits() + "條");

        Iterator<SearchHit> iterator = hits.iterator();

        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每個查詢對象

            System.out.println(searchHit.getSourceAsString()); // 獲取字符串格式打印
        }

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

控制檯打印:
在這裏插入圖片描述


【9】映射mappings

上面創建的索引默認映射信息http://192.168.18.128:9200/my-blog?pretty
在這裏插入圖片描述
添加mapping的索引必須存在且該索引不能存在mapping,否則添加不成功。

實例代碼:

	 @Test
    public void createMapping() throws Exception {
        //1.添加mapping的索引必須存在;2.該索引不能存在mapping,否則添加不成功
        CreateIndexResponse blog = client.admin().indices().prepareCreate("my-blog2").get();
        System.out.println(blog);

        // 2設置mapping
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id1")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .startObject("title2")
                .field("type", "string")
                .field("store", "no")
                .endObject()
                .startObject("content")
                .field("type", "string")
                .field("store", "yes")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        // 3 添加mapping
        PutMappingRequest mapping = Requests.putMappingRequest("my-blog2").type("article").source(builder);

        client.admin().indices().putMapping(mapping).get();

        // 4 關閉資源
        client.close();
    }

瀏覽器查詢確認http://192.168.18.128:9200/_cat/indices
在這裏插入圖片描述
查詢索引明細http://192.168.18.128:9200/my-blog2?pretty
在這裏插入圖片描述

總結,用java原生操作es十分麻煩,建議使用SpringData Elasticsearch官網

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