elasticsearch常用JAVA API 实例

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;
    }
}
复制代码

 

posted @ 2018-08-07 18:52  华丽D转身  阅读(1866)  评论(0编辑  收藏  举报