1. 程式人生 > >elasticsearch常用JAVA API 實例

elasticsearch常用JAVA API 實例

tool actor tag 測試 實體類 sea isp nan del

1.引入dependency

技術分享圖片
<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>1.4.0.M1</version>
</dependency>

2:創建\添加索引

技術分享圖片 View Code

技術分享圖片

3.創建實體類

技術分享圖片 技術分享圖片
package testweb;

import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName="yananindex",type="yanantype")
public class Yanan {
    private int id;
    private String name;
    private String gender;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }    
}
技術分享圖片

準備工作做完了,下面開始測試

4.queryForObject\queryForList\聚合查詢\統計數量\判斷索引是否存在\刪除指定id的索引

技術分享圖片 技術分享圖片
package testweb;

import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ResultsExtractor;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

public class TestES {
    static TransportClient transportClient;
    static ElasticsearchTemplate elasticsearchTemplate;

    public static void main(String[] args) {
        elasticsearchTemplate=getElasticsearchTemplate("localhost","elasticsearch_bak",9303);
        //queryForObject();//根據索引id查詢文檔
        //queryForList();
        //aggregationQuery();//聚合查詢
        //count();
        //indexExists(Yanan.class);
        deleteById();
    }
    private static void deleteById() {
    //    IndexQueryBuilder indexquery=new IndexQueryBuilder().withId("1").withObject(Yanan.class);
        //String delete = elasticsearchTemplate.delete("yananindex", "yanantype", "10");//索引的id
        String delete = elasticsearchTemplate.delete(Yanan.class, "10");//索引的id
        System.out.println(delete);//刪除的索引的id
    }
    private static void indexExists(Class<Yanan> clazz) {
        if(elasticsearchTemplate.indexExists(clazz)){
            System.out.println("true");
        }else{
            System.out.println(false);
        }
    }
    private static void count() {
        NativeSearchQueryBuilder searchQuery=new NativeSearchQueryBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.termQuery("gender","female"));
        searchQuery.withIndices("yananindex").withQuery(bqb);
        long count = elasticsearchTemplate.count(searchQuery.build());
        System.out.println(count);
    }
    
    private static void aggregationQuery() {
        TermsBuilder termsBuilder = AggregationBuilders.terms("maleCount").field("name").size(10);
        NativeSearchQueryBuilder searchQuery=new NativeSearchQueryBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.termQuery("gender","male"));
        searchQuery.withIndices("yananindex").withQuery(bqb).addAggregation(termsBuilder);
        Aggregations aggregations = elasticsearchTemplate.query(searchQuery.build(), new ResultsExtractor<Aggregations>() {
            @Override
            public Aggregations extract(SearchResponse response) {
                return  response.getAggregations();
            }
        });
        StringTerms modelTerms = (StringTerms)aggregations.asMap().get("maleCount");
        List<Bucket> buckets = modelTerms.getBuckets();
        for(int i=0;i<buckets.size();i++){
            System.out.println(buckets.get(i).getKey()+"\t"+buckets.get(i).getDocCount());
        }
    }
    private static void queryForList() {
        NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.termQuery("gender","male"));
        searchQuery.withIndices("yananindex").withQuery(bqb);
        List<Yanan> list = elasticsearchTemplate.queryForList(searchQuery.build(), Yanan.class);
        for(int i=0;i<list.size();i++){
            Yanan yanan = list.get(i);
            System.out.println(yanan.getName()+"\t"+yanan.getGender()+"\t"+yanan.getId());
        }
        
    }
    private static void queryForObject() {
        GetQuery query = new GetQuery();
        query.setId("1");// 索引的id
        Yanan yanan = elasticsearchTemplate.queryForObject(query, Yanan.class);
        System.out.println(yanan.getGender());
        System.out.println(yanan.getName());
        System.out.println(yanan.getId());// 實體的id
    }
    
    static ElasticsearchTemplate getElasticsearchTemplate(String ip,String clusterName,int port){//<a href="http://blog.csdn.net/ty4315/article/details/52434296" target="_blank">@參考文章1</a>,<a href="http://blog.csdn.net/ljc2008110/article/details/48630609" target="_blank">@參考文章2</a>
        Settings setting = ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)// 指定集群名稱
                .put("client.transport.sniff", true)// 啟動嗅探功能,客戶端去嗅探整個集群的狀態,把集群中其它機器的ip地址加到客戶端中,這樣做的好處是一般你不用手動設置集群裏所有集群的ip到連接客戶端,它會自動幫你添加,並且自動發現新加入集群的機器。
                .build();
        // 創建客戶端 通過setting來創建,若不指定則默認鏈接的集群名為elasticsearch 鏈接使用tcp協議即9303
        transportClient = new TransportClient(setting);
        TransportAddress transportAddress = new InetSocketTransportAddress(ip, port);
        transportClient.addTransportAddresses(transportAddress);
        elasticsearchTemplate = new ElasticsearchTemplate(transportClient);
        return elasticsearchTemplate;
    }
}
技術分享圖片

elasticsearch常用JAVA API 實例