ElasticSearch常用操作Java api

15898 ワード

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @Description :ElasticSearch    Java api
 * @Author: lyw
 * @Date: 2019/1/15 11:27
 * @Version 1.0
 */
public class ESTest {
    // es   
    private Client client;

    @Before
    public void getClient() throws Exception {
        //     es   
        //   :  es       elasticsearch,       
        final HashMap map = new HashMap<>();
        map.put("cluster.name", "es");
        final Settings.Builder settings = Settings.builder().put(map);
        // es java api      9300
        //          ,                     ,            
        client = TransportClient.builder().settings(settings).build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop01"), 9300))
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop02"), 9300))
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop03"), 9300));
    }

    /**
     *   json          
     */
    @Test
    public void createDoc_1() {
        // json   
        String source = "{" +
                "\"id\":\"1\"," +
                "\"title\":\"ElasticSearch     Lucene      \"," +
                "\"content\":\"                     ,  RESTful web  \"}";
        //     ,    、    、  id
        final IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(source).get();//      execute().actionGet()

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

        client.close();
    }

    /**
     *   map    
     */
    @Test
    public void createDoc_2() {
        final HashMap source = new HashMap<>();
        source.put("id", 2);
        source.put("title", "ElasticSearch");
        source.put("content", "             ,        ");

        final IndexResponse indexResponse = client.prepareIndex("blog", "article", "2").setSource(source).get();

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

        client.close();
    }

    /**
     *   es        
     */
    @Test
    public void createDoc_3() throws Exception {
        final XContentBuilder source = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", 3)
                .field("title", "Lucene      ")
                .field("content", "   Apache            ")
                .endObject();

        client.prepareIndex("blog", "article", "3").setSource(source).get();

        client.close();
    }


    /**
     *     ,    
     */
    @Test
    public void getData_1() {
        final GetResponse getResponse = client.prepareGet("blog", "article", "1").get();
        System.out.println(getResponse.getSourceAsString());

        client.close();
    }

    /**
     *     ,    
     */
    @Test
    public void getData_2() {
        final MultiGetResponse multiGetResponse = client.prepareMultiGet()
                .add("blog", "article", "1")
                .add("blog", "article", "2")
                .add("blog", "article", "100")
                .get();

        //   
        for (MultiGetItemResponse multiGetItemResponse : multiGetResponse) {
            final GetResponse response = multiGetItemResponse.getResponse();
            //         
            if (response.isExists())
                System.out.println(response.getSourceAsString());
        }


        client.close();
    }

    /**
     *     
     */
    @Test
    public void updateData_1() throws Exception {
        final UpdateRequest request = new UpdateRequest();
        request.index("blog");
        request.type("article");
        request.id("1");
        request.doc(XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "1")
                .field("title", "  :ElasticSearch     Lucene      ")
                .field("content", "  :                     ,  RESTful web  ")
                .endObject());

        client.update(request).get();

        client.close();
    }

    /**
     *     
     */
    @Test
    public void updateData_2() throws Exception {
        client.update(new UpdateRequest("blog", "article", "2")
                .doc(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("id", "2")
                        .field("title", "  :ElasticSearch")
                        .field("content", "  :             ,        ,  RESTful web  ")
                        .endObject())).get();


        client.close();
    }

    /**
     *       ,          ,  id,       ,   ,    ,   
     */
    @Test
    public void updateDate_3() throws Exception {
        final IndexRequest source = new IndexRequest("blog", "article", "4")
                .source(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("id", "4")
                        .field("title", "           JSON")
                        .field("content", "                ")
                        .endObject());
        //        
        final UpdateRequest upsert = new UpdateRequest("blog", "article", "4")
                .doc(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("title", "ElasticSearch     Lucene      ")
                        .endObject())
                .upsert(source);

        client.update(upsert).get();

        client.close();
    }

    /**
     *       
     */
    @Test
    public void deleteData() {
        client.prepareDelete("blog", "article", "3").get();

        client.close();
    }

    /**
     *   :SearchResponse,      
     */
    @Test
    public void search() {

        //               (es       ),            
        // queryStringQuery  ,          
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("  ")) //              
                .get();

        //           ,        
        final SearchHits hits = searchResponse.getHits();

        System.out.println("      " + hits.getTotalHits() + " ");

        //       
        final Iterator it = hits.iterator();
        while (it.hasNext()) {
            final SearchHit searchHit = it.next();
            System.out.println("     :" + searchHit.getSourceAsString());
            //          
            System.out.println("id:" + searchHit.getId()); //    id        _id
            System.out.println("id:" + searchHit.getSource().get("id"));
            System.out.println("title:" + searchHit.getSource().get("title"));
            System.out.println("content:" + searchHit.getSource().get("content"));
        }

        client.close();
    }

    /**
     *     (ik     )
     */
    @Test
    public void createIndex() {
        //     
        client.admin().indices().prepareCreate("blog").get();
        //     
//        client.admin().indices().prepareDelete("blog").get();

    }

    /**
     *     ,     
     */
    @Test
    public void createIndexMapping() throws Exception {
        final XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id")
                .field("type", "integer").field("store", "yes")
                .endObject()
                .startObject("title")
                .field("type", "string").field("store", "yes").field("analyzer", "ik")
                .endObject()
                .startObject("content")
                .field("type", "string").field("store", "yes").field("analyzer", "ik")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        final PutMappingRequest source = Requests.putMappingRequest("blog")
                .type("article")
                .source(mappingBuilder);

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

        client.close();
    }


    /**
     *   :    
     */
    @Test
    public void queryAll(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery())
                .get();

        this.getResponse(searchResponse);
        client.close();
    }

    /**
     *   :       
     */
    @Test
    public void queryString(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("  ").field("content").field("title"))
                .get();

        this.getResponse(searchResponse);
        client.close();
    }

    /**
     *      (    )
     */
    @Test
    public void wildcardQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.wildcardQuery("content", "  ? ")) // ?     *     
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     *     
     */
    @Test
    public void termQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
//                .setQuery(QueryBuilders.termQuery("title", "  "))
                .setQuery(QueryBuilders.termsQuery("title","  ","  ")) //                 
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     *       
     */
    @Test
    public void fieldMatchQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                //              ,               
               // .setQuery(QueryBuilders.matchQuery("title"," ").analyzer("ik").fuzziness(1)) //                 
                //             
               // .setQuery(QueryBuilders.matchPhrasePrefixQuery("title"," "))
                //          
                .setQuery(QueryBuilders.multiMatchQuery("  ","title","content"))
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     * id  
     */
    @Test
    public void idQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.idsQuery().ids("2","4"))
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     *       (    )
     */
    @Test
    public void fuzzyQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("title","Lusene")) //      Lucene
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     *     
     */
    @Test
    public void rangeQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
               // .setQuery(QueryBuilders.rangeQuery("id").gte(1).lte(3)) //     1    3
                .setQuery(QueryBuilders.rangeQuery("id").from(1).to(3)) //     1    3
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     * bool               
     */
    @Test
    public void boolQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.termQuery("title","  "))
                                .should(QueryBuilders.rangeQuery("id").from(1).to(3))
                )
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    /**
     *     ,          
     */
    @Test
    public void sortQuery(){
        final SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.termQuery("title","  "))
                                .should(QueryBuilders.rangeQuery("id").from(1).to(3))
                ).addSort("id", SortOrder.DESC)
                .get();
        this.getResponse(searchResponse);
        client.close();

    }

    //   
    public void getResponse(SearchResponse searchResponse){

    }


}