Java代碼操作Elasticsearch


創建maven項目,導入依賴

     <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.8</version>
        </dependency>

 

連接所有方法都要用,提成公共方法

public TransportClient getClient() throws UnknownHostException {
        //步驟一:創建一個Settings對象,指定集群名字
        Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
        //步驟二:創建一個Client連接對象
        TransportClient client = new PreBuiltTransportClient(settings);
        //步驟三:連接到ES服務器
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        return client;
    }

 

  1.創建一個空的索引庫

/**
     * 創建空的索引庫
     */
    @Test
    public void createNullIndex() throws UnknownHostException {
        TransportClient client = getClient();
        //創建一個空的索引庫  admin()管理權限    indices()索引庫   prepareCreate()創建一個索引庫   get()執行之前的操作請求
        client.admin().indices().prepareCreate("y2170").get();
        //關閉client對象
        client.close();
    }

 


        
        2.索引庫指定Mapping信息
            2.1 利用XContentBuilder對象拼接JSON字符串
            2.2 手動用過字符串拼接得到JSON字符串

                {
                        "hello":{
                            "properties":{
                                "id":{
                                    "type":"long",
                                    "store":true,
                                    "index":"not_analyzed"
                                },
                                "title":{
                                    "type":"text",
                                    "store":true,
                                    "index":"analyzed",
                                    "analyzer":"ik_max_word"
                                },
                                "content":{
                                    "type":"text",
                                    "store":true,
                                    "index":"analyzed",
                                    "analyzer":"ik_max_word"
                                }
                            }    
                        }
                }

 


                案例:
               

/**
                 * 指定索引庫的Mapping信息
                 */
                @Test
                public void createMappingByIndex() throws IOException {
                    TransportClient client = getClient();
                    //創建一個XContentBuilder對象,用於拼接JSON格式字符串
                    XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
                    xContentBuilder.startObject().startObject("hello").startObject("properties")
                            .startObject("id").field("type","long").field("store",true).field("index","not_analyzed").endObject()
                            .startObject("title").field("type","text").field("store",true).field("index","analyzed").field("analyzer","ik_max_word").endObject()
                            .startObject("content").field("type","text").field("store",true).field("index","analyzed").field("analyzer","ik_max_word").endObject()
                            .endObject().endObject().endObject();
                    //指定索引庫以及Type類型的Mapping映射信息  preparePutMapping代表向哪一個索引庫指定mpiing信息     setType代表該索引庫下的TYPE,與上方JSON創建的Type保持一致
                    //setSource 指定JSON字符串的存儲對象   get執行
                    client.admin().indices().preparePutMapping("y2170").setType("hello").setSource(xContentBuilder).get();

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

 

 

        3.創建索引庫同時指定Mapping信息

            /**
             * 創建索引庫並且指定Mapping信息
             */
            @Test
            public void createIndexAndMapping() throws IOException {
                TransportClient client = getClient();
                //創建索引庫
                client.admin().indices().prepareCreate("wdksoft").get();
                //創建Mapping信息
                //創建一個XContentBuilder對象,用於拼接JSON格式字符串
                XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
                xContentBuilder.startObject().startObject("article").startObject("properties")
                        .startObject("id").field("type","long").field("store",true).field("index","not_analyzed").endObject()
                        .startObject("title").field("type","text").field("store",true).field("index","analyzed").field("analyzer","ik_max_word").endObject()
                        .startObject("content").field("type","text").field("store",true).field("index","analyzed").field("analyzer","ik_max_word").endObject()
                        .endObject().endObject().endObject();


                client.admin().indices().preparePutMapping("wdksoft").setType("article").setSource(xContentBuilder).get();

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

 

        4.刪除索引庫
          

 /**
             * 刪除索引庫
             */
            @Test
            public void deleteIndex() throws UnknownHostException {
                 TransportClient client = getClient();
                 //刪除索引庫
                 client.admin().indices().prepareDelete("wdksoft").get();

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

 


        
        
        
        5.創建文檔-通過XContentBuilder對象拼接JSON格式字符串
       (  {  ) 開頭用.startObject()

  (  }  )結尾用.endObject()

  域用.field(鍵,值),多個就繼續在后面追加

 /**
             * 創建文檔-通過XContentBuilder對象拼接JSON字符串
             */
            @Test
            public void createDocumentByXC() throws IOException {
                TransportClient client = getClient();
                //構建文檔信息
                XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
                xContentBuilder.startObject().field("id",1).field("title","Lucene是apache軟件基金會4 jakarta項目組的一個子項目")
                        .field("content","Lucene是apache軟件基金會4 jakarta項目組的一個子項目,是一個開放源代碼的全文檢索引擎工具包,但它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的")
                        .endObject();
                //創建文檔
                client.prepareIndex("y2170","hello","1").setSource(xContentBuilder).get();
                client.close();
            }

 

 


        
        6.創建文檔-通過對象轉換為JSON字符串

Hello類

public class Hello {
    private Integer id;     //屬性要跟Type的域的名字一致
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Hello(Integer id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public Hello() {
    }
}

 

 

/**
             * 創建文檔-通過對象轉換成JSON字符串
             * fastjson  String helloJson = JSON.toJSONString(hello);
             * jackson
             *      ObjectMapper objectMapper=new ObjectMapper();
             *      String helloJson = objectMapper.writeValueAsString(hello);
             */
            @Test
            public void createDocumentByObject() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();

                //准備一個數據(文檔)對象
                Hello hello=new Hello(3,"ElasticSearch是一個基於Lucene的搜索服務器","ElasticSearch是一個基於Lucene的搜索服務器。它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口。Elasticsearch是用Java語言開發的,並作為Apache許可條款下的開放源碼發布,是一種流行的企業級搜索引擎。ElasticSearch用");
                //將對象轉換為JSON格式字符串  fastjson
                /*String helloJson = JSON.toJSONString(hello);
                System.out.println(helloJson);*/

                //利用jackson轉換
                ObjectMapper objectMapper=new ObjectMapper();
                String helloJson = objectMapper.writeValueAsString(hello);
                //向索引庫中添加文檔數據
                client.prepareIndex("y2170","hello","3").setSource(helloJson, XContentType.JSON).get();
                client.close();
            }
        

 


        
           
        
        7.刪除文檔

            /**
             * 刪除文檔
             */
            @Test
            public void deleteDocument() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();

                //刪除文檔
                client.prepareDelete("y2170","hello","4").get();

                client.close();
            }

 


        
        
        8.查詢文檔-根據文檔ID查詢
           

/**
             * 根據文檔ID進行查詢
             */
            @Test
            public void getDocumentByID() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();
                //執行查詢,可查詢多個
                SearchResponse searchResponse = client.prepareSearch("y2170").setTypes("hello").setQuery(
                        QueryBuilders.idsQuery().addIds("1", "2")
                ).get();
                //獲取到查詢結果
                SearchHits hits = searchResponse.getHits();
                //如果返回數據較多,默認進行分頁,默認10條數據
                System.out.println("獲取到文檔數據條目數:"+hits.getTotalHits());
                //獲取到文檔數據
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    System.out.println(hit.getSourceAsString());
                    System.out.println("content:"+hit.getSource().get("content"));
                }

                client.close();
            }

 


        
        9.查詢文檔-根據Term關鍵詞查詢
          

 /**
             * 根據Term分詞進行查詢
             */
            @Test
            public void getDocumentByTerm() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();
                //執行查詢,可查詢多個
                SearchResponse searchResponse = client.prepareSearch("y2170").setTypes("hello").setQuery(
                        QueryBuilders.termQuery("title","服務器")
                ).get();
                //獲取到查詢結果
                SearchHits hits = searchResponse.getHits();
                //如果返回數據較多,默認進行分頁,默認10條數據
                System.out.println("獲取到文檔數據條目數:"+hits.getTotalHits());
                //獲取到文檔數據
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    System.out.println(hit.getSourceAsString());
                    System.out.println("content:"+hit.getSource().get("content"));
                }

                client.close();
            }

 


        
        
        10.查詢文檔-根據QueryString查詢文檔
          

 @Test
            public void getDocumentByQueryString() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();
                //執行查詢
                SearchResponse searchResponse = client.prepareSearch("y2170").setTypes("hello").setQuery(
                        QueryBuilders.queryStringQuery("Solr是一個獨立的企業級搜索應用服務器")
                ).get();
                //獲取到查詢結果
                SearchHits hits = searchResponse.getHits();
                //如果返回數據較多,默認進行分頁,默認10條數據
                System.out.println("獲取到文檔數據條目數:"+hits.getTotalHits());
                //獲取到文檔數據
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    System.out.println(hit.getSourceAsString());
                    System.out.println("content:"+hit.getSource().get("content"));
                }

                client.close();
            }

 


        
        11.查詢數據的分頁檢索
            ES當中默認檢索數據是10條
          

 /**
             * 分頁
             */
            @Test
            public void getDocumentByQueryStringlimit() throws UnknownHostException, JsonProcessingException {
                TransportClient client = getClient();
                //設置查詢條件
                SearchRequestBuilder searchRequestBuilder = client.prepareSearch("y2170").setTypes("hello").setQuery(
                        QueryBuilders.queryStringQuery("服務器")
                );
                //加入分頁規則       setFrom代表從那一條數據開始獲取
                searchRequestBuilder.setFrom(0).setSize(5);
                SearchResponse searchResponse = searchRequestBuilder.get();
                //獲取到查詢結果
                SearchHits hits = searchResponse.getHits();
                //如果返回數據較多,默認進行分頁,默認10條數據
                System.out.println("獲取到文檔數據條目數:" + hits.getTotalHits());
                //獲取到文檔數據
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()) {
                    SearchHit hit = iterator.next();
                    System.out.println(hit.getSourceAsString());
                    System.out.println("content:" + hit.getSource().get("content"));
                }

                client.close();
            }

 

 


        
        12.查詢數據的高亮顯示
            執行查詢數據之前設置高亮顯示規則
                1.設置高亮顯示的域
                2.設置高亮顯示前綴
                3.設置高亮顯示后綴
            執行查詢
            獲取到高亮顯示的數據
          

  /**
                 * 高亮顯示
                 */
                @Test
                public void getDocumentByQueryHight() throws UnknownHostException, JsonProcessingException {
                    TransportClient client = getClient();
                    //設置查詢條件
                    SearchRequestBuilder searchRequestBuilder = client.prepareSearch("y2170").setTypes("hello").setQuery(
                            QueryBuilders.termQuery("title", "服務器")
                    );
                    //加入分頁規則       setFrom代表從那一條數據開始獲取
                    searchRequestBuilder.setFrom(0).setSize(5);
                    //設置高亮規則
                    HighlightBuilder highlightBuilder=new HighlightBuilder();
                    //指定高亮顯示的域
                    highlightBuilder.field("title");
                    highlightBuilder.preTags("<span style='color:red'>");
                    highlightBuilder.postTags("</span>");
                    searchRequestBuilder.highlighter(highlightBuilder);
                    //執行查詢
                    SearchResponse searchResponse = searchRequestBuilder.get();
                    //獲取到查詢結果
                    SearchHits hits = searchResponse.getHits();
                    //如果返回數據較多,默認進行分頁,默認10條數據
                    System.out.println("獲取到文檔數據條目數:" + hits.getTotalHits());
                    //獲取到文檔數據
                    Iterator<SearchHit> iterator = hits.iterator();
                    while (iterator.hasNext()) {
                        SearchHit hit = iterator.next();
                        System.out.println(hit.getSourceAsString());
                        /* System.out.println("content:" + hit.getSource().get("content"));*/

                        //獲取高亮結果
                        Text[] titles = hit.getHighlightFields().get("title").getFragments();
                        for(Text text:titles){
                            System.out.println("高亮顯示數據為:"+text);
                        }
                    }

                    client.close();
                }

 

數據到網頁中,通過改變樣式

就可達到高亮顯示數據的目的

 


免責聲明!

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



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