Elasticsearch 의 추가 삭제,페이지,하 이 라이트 조회(maven)

12008 단어 기술 창고es
전제:es 환경(es 서비스,IK 중국어 단어 기,head-master 플러그 인 등)을 구축 하 십시오.
환경 준비
pom 파일 에서 좌 표를 가 져 옵 니 다(첫 번 째 가 져 오 는 시간 이 좀 길 수 있 습 니 다.기 다 려 주 십시오) 
 
        
            org.elasticsearch.client
            transport
            5.6.8
        
        
            junit
            junit
            4.12
        
        
            com.alibaba
            fastjson
            1.2.56
        
    

문서 주석 에 따라 삭제 및 페이지 나 누 기,하 이 라이트 조 회 를 완성 할 수 있 습 니 다.
코드 에 실체 클래스 를 사 용 했 습 니 다.자체 적 으로 실체 클래스 를 만 들 면 get/set 방법 과 toString 방법 을 제공 합 니 다.
package com.itcode.test2;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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


public class InitEsData {
    public static TransportClient transportClient;

    @Before
    public void init() throws Exception {
        //         
        transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    }

    @After
    public void destory() {
        transportClient.close();
    }

    //           
    @Test
    public void createIndex() throws IOException {
        transportClient.admin().indices().prepareCreate("blog2").get();
    }

    //    
    @Test
    public void daleteIndex() {
        transportClient.admin().indices().prepareDelete("blog2").get();
    }

    //          
    @Test
    public void testCreateSearchIndex() throws ExecutionException, InterruptedException, IOException {
        IndicesExistsResponse blog2 = transportClient.admin().indices().prepareExists("blog2").get();
        if (!blog2.isExists()) {
            CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
        }
        //    
        /**
         *
         *   :
         *  "mappings" :
         *       
         *   {
         *      "article" : {
         *          "properties" : {
         *              "id" : { "type" : "long", "store":"yes" },
         *              "content" : { "type" : "string" , "store":"yes" , "analyzer":"ik_smart"},
         *              "title" : { "type" : "string", "store":"yes" , "analyzer":"ik_smart" }
         *           }
         *       }
         *   }
         */
        //     :
/*
        Map id = new HashMap();
        id.put("type", "long");
        id.put("store", "yes");

        Map content = new HashMap();
        content.put("type","string");
        content.put("store","yes");
        content.put("analyzer","ik_smart");

        Map title = new HashMap();
        title.put("type","string");
        title.put("store","yes");
        title.put("analyzer","ik_smart");

        Map properties = new HashMap();
        properties.put("id",id);
        properties.put("content",content);
        properties.put("title",title);

        Map articles = new HashMap();
        articles.put("properties",properties);

        Map mapping = new HashMap();
        mapping.put("articles",articles);
        PutMappingRequest request = Requests.putMappingRequest("blog2").type("articles").source(mapping);
*/

        //      XContentFactory  json     (    )
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id")
                .field("type", "long")
                .field("store", "yes")
                .endObject()
                .startObject("title")
                .field("type", "string")
                .field("store", "yes")
                .field("analyzer", "ik_smart")
                .endObject()
                .startObject("content")
                .field("type", "string")
                .field("store", "yes")
                .field("analyzer", "ik_smart")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        PutMappingRequest request = Requests.putMappingRequest("blog2").type("article").source(builder);
        PutMappingResponse putMappingResponse = transportClient.admin().indices().putMapping(request).get();
        System.out.println(putMappingResponse.isAcknowledged());

    }

    //    
    @Test
    public void createDocument() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject()
                .field("id", 1L)
                .field("title", "ElasticSearch     Lucene      ")
                .field("content", "                     ,  RESTful web  。Elasticsearch   Java   ,   Apache            ,             。        ,         ,  ,  ,  ,      。")
                .endObject();
        transportClient.prepareIndex("blog2", "article", "1").setSource(builder).get();
    }

    //      document
    @Test
    public void createDocumentByObject() {
        Article article = new Article();
        article.setId(2L);
        article.setTitle("           ");
        article.setContent("               ,                      ,           JSON  HTTP     ,                ,                ,       ,         ,              。Elasticsearch                。");

        String jsonString = JSON.toJSONString(article);

        transportClient.prepareIndex("blog2", "article", article.getId() + "")
                .setSource(jsonString, XContentType.JSON).get();

    }

    //    

    /**
     *       ,    prepareIndex.   id                  
     *      prepareUpdate    ,      update   
     */
    @Test
    public void updateDocumentByObject() throws ExecutionException, InterruptedException {
        Article article = new Article();
        article.setId(2L);
        article.setTitle("           ");
        article.setContent("ok,               ,                      ,           JSON  HTTP     ,                ,                ,       ,         ,              。Elasticsearch                。");

        String jsonString = JSON.toJSONString(article);
        UpdateResponse response = transportClient.prepareUpdate("blog2", "article", article.getId() + "").setDoc(jsonString, XContentType.JSON).get();
//        UpdateResponse response = transportClient.update(new UpdateRequest("blog2", "article", article.getId()+"").doc(jsonString, XContentType.JSON)).get();
        System.out.println(response.status());
    }


    //    
    @Test
    public void deleteDocument() throws ExecutionException, InterruptedException {
        //DeleteResponse response = transportClient.prepareDelete("blog2", "article", "2").get();
        DeleteResponse response = transportClient.delete(new DeleteRequest("blog2", "article", "2")).get();
        System.out.println(response.status());
    }

    //      
    @Test
    public void addData(){
        for (int i = 0; i < 100; i++) {
            Article article = new Article();
            article.setId((long)i);
            article.setTitle(i + "             ");
            article.setContent(i+"               ,                      ,           JSON  HTTP     ,                ,                ,       ,         ,              。Elasticsearch                。");


            IndexResponse response = transportClient.prepareIndex("blog2", "article", article.getId() + "").setSource(JSON.toJSONString(article), XContentType.JSON).get();


        }
    }

    //       
    @Test
    public void searchPage() {
        SearchRequestBuilder builder = transportClient.prepareSearch("blog2").setTypes("article").setQuery(QueryBuilders.matchAllQuery());

        //    (pageNum-1)*pageSize
        //from        ,size    
        builder.setFrom(0).setSize(10);
        //                  
        builder.addSort("id", SortOrder.DESC);

        SearchResponse response = builder.get();
        //    
        SearchHits hits = response.getHits();
        //     
        System.out.println(hits.getTotalHits());
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
            System.out.println(hit.getSource().get("title"));
        }
    }
    //        
    @Test
    public void hightlightQuery(){
        //           term    ,       
        SearchRequestBuilder builder = transportClient.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.termQuery("content","  "));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        highlightBuilder.field("content");
        builder.highlighter(highlightBuilder);
        SearchResponse response = builder.get();

        SearchHits hits = response.getHits();
        System.out.println("   "+hits.getTotalHits());
        for (SearchHit hit : hits) {
            Text[] contents = hit.getHighlightFields().get("content").getFragments();
            for (Text content : contents) {
                System.out.println(content);
            }

        }

    }
}

좋은 웹페이지 즐겨찾기