JAVA API查找和添加elasticsearch內容


本章主要講解一種添加和三種查找功能,我們分別以代碼形式進行講解,歡迎各位積極討論。

首先,應用java導包是必須的,我們創建maven項目后,在pom.xml文件中,進行導包。所需要包可在maven elasticsearch官網查詢。

 

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>6.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>

</dependencies>

 

導包完成后,即可進行下面的步驟。

 

1.ES文本內容的添加jsonBuilder(

2.ES文本內容查找:

  (1)全文查詢:SearchResponse-preparesearch

  (2)模糊查詢:QueryBuilders()

  (3)聚合查詢:AggregationBuilders()

下面開始代碼講解:

1.文本添加

 

import...
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class Demol4 {
    public static void main(String[] args) throws Exception {
        TransportClient client=new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
                ;

        XContentBuilder builder = jsonBuilder()
                .startObject()
                .field("first_name", "gou gou")
                .field("last_name","smith")
                .field("about", "trying out Elasticsearch")
                .field("interests","music,act")
                .endObject();
        IndexResponse response=client.prepareIndex("megacorp","employee").setSource(builder).get();
        System.out.println(response);
        client.close();

    }
}

 

在一個main方法中,我們首先需要用TransportClient的子類PreBuiltTransportClient去連接我們的elasticsearch,注意java連接es的端口號是9300。治理這里是以new對象的形式進行使用,並設置為空,通過IP地址添加新的連接。

  文本添加的jsonBuilder是以對象的開始(startObject)和結束(endObject)為標志,在其中以屬性field的方式添加。其中添加的需要有name和value。內容填寫完畢后,需要增加到elasticsearch中,使用索引IndexResponse類型的prepareIndex方法,參數為地址索引和類型索引,將文件添加是setSource(對象).get()。

  這樣就將文件添加到了elasticsearch中,並可以查詢了。

2.全文查詢

 

public class Demol1 {
    public static void main(String[]args)throws Exception{
        TransportClient client=new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
                ;
        SearchResponse response=client.prepareSearch("megacorp").setTypes("employee").get();
        System.out.print(response);
        SearchHit[] hits=response.getHits().getHits();

        for(SearchHit sh:hits){
            System.out.println();
            Map<String,Object> data=sh.getSourceAsMap();
            String full_name=data.get("first_name")+"."+data.get("last_name");
            String age=data.get("age").toString();
            String about=data.get("about").toString();
            List<String> interests= (List<String>) data.get("interests");
            System.out.println(full_name+"\t"+age+"\t"+about);
            for(String like:interests){
                System.out.println(like);
            }
            System.out.println("---------------");
        }
        client.close();

    }
}

 

l連接部分不再贅述,查找內容,首先需要用SearchResponse類型的prepareSearch()方法找到相應的類型文檔,以get()方法獲取。獲取的內容以數組形式SearchHit【】存儲在hits中。通過getHist方法的重復使用,直接得到屬性處的文本內容。

  對文本內容進行迭代輸出,並以Map的形式接收,應用getSourceAsMap()方法。聲明變量為得到的屬性對應值,數組形式的變量以List<>數組形式接收並迭代輸出。最終得到所有文本中,關於定義變量的屬性對應的內容。

3.模糊查詢

 

public class Demol3 {
    public static void main(String[] args) throws Exception {
        TransportClient client=new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
                ;

        SearchResponse response=client.prepareSearch("megacorp").setTypes("employee").setQuery(
                 QueryBuilders.termsQuery("last_name","smith")
    //單條信息的查詢,不適合在聚合情況下的查詢,需要知道vlaue包含的值

        ).get();
        System.out.println(response);
        client.close();

    }
}

 

  模糊查詢的應用一樣也是get()方法獲取,不同的是,需要中間加入setQuery方法,並應用QueryBuilders.termsQuery()方法獲取模糊查詢的內容。其中需要知道屬性以及屬性內包含的值。然后可以直接輸出。

4.聚合查詢

 

public class Demol2 {
    public static void main(String[] args) throws Exception {
        TransportClient client=new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
                ;

        SearchResponse response=client.prepareSearch("megacorp").setTypes("employee").addAggregation(
                AggregationBuilders.terms("all_interests").field("interests").subAggregation(
                        AggregationBuilders.avg("avg_age").field("age")
                )
        ).execute().actionGet();
        System.out.println(response);
        client.close();

    }
}

 

與模糊查詢類似,只是方法需要改變,聚合查詢的方法是通過添加聚合addAggregation()方法,並用AggregationBuilders方法,對聚合內部的屬性進行查找,聚合屬性可能是terms,也可能是avg,這要根據文檔查詢內容進行匹配。不同的是,聚合查找的屬性值通過terms或avg確定后,屬性值需要通過field方法進行跟進。

  對於嵌套式的聚合內容,執行在后面繼續增加subAggregation方法,內部寫法均類似。大多數聚合一般為兩層最深,如果遇到更深層次的聚合,套用即可。

說一下,這里的execute().actionnGet()=get(),內部可以做參數的配置,包括等待時間time等。最后記得關閉連接的client。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM