ElasticSearch Java Client Demo

關係型數據庫和ElasticSearch概念對應關係java

Relational DB ElasticSearch
Database Indice
Tables Types
Rows Documents
Cloumns Fields

 

首先在maven pom.xml中引入ElasticSearch java client 的jar包:數據庫

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.6.2</version>
        </dependency>

單元測試代碼:apache

package sxq.demo;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

public class ElasticSearchTest {
    TransportClient client;
    @Before
    @SuppressWarnings({ "unchecked" })
    public void before() throws UnknownHostException, InterruptedException, ExecutionException {
        Settings esSettings = Settings.builder()
                .put("cluster.name", "elasticsearch") //設置ES實例的名稱
                .put("client.transport.sniff", true) //自動嗅探整個集羣的狀態,把集羣中其餘ES節點的ip添加到本地的客戶端列表中
                .build();
        client = new PreBuiltTransportClient(esSettings);//初始化client較老版本發生了變化,此方法有幾個重載方法,初始化插件等。
        //此步驟添加IP,至少一個,其實一個就夠了,由於添加了自動嗅探配置
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    }
    
    @Test
    public void index() throws Exception {
        Map<String,Object> infoMap = new HashMap<String, Object>();
        infoMap.put("name", "廣告信息11");
        infoMap.put("title", "個人廣告22");
        infoMap.put("createTime", new Date());
        infoMap.put("count", 1022);
        IndexResponse indexResponse = client.prepareIndex("test", "info","100").setSource(infoMap).execute().actionGet();
        System.out.println("id:"+indexResponse.getId());
    }
    
    @Test
    public void get() throws Exception {
        GetResponse response = client.prepareGet("sxq", "user", "2")  
                .execute().actionGet();  
        System.out.println("response.getId():"+response.getId());  
        System.out.println("response.getSourceAsString():"+response.getSourceAsString());  
    }
    
    @Test
    public void query() throws Exception {
        //term查詢
//        QueryBuilder queryBuilder = QueryBuilders.termQuery("age", 50) ;
        //range查詢
        QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gt(50);
        SearchResponse searchResponse = client.prepareSearch("sxq")
                .setTypes("user")
                .setQuery(rangeQueryBuilder)
                .addSort("age", SortOrder.DESC)
                .setSize(20)
                .execute()
                .actionGet();
        SearchHits hits = searchResponse.getHits(); 
        System.out.println("查到記錄數:"+hits.getTotalHits());
        SearchHit[] searchHists = hits.getHits();
        if(searchHists.length>0){
            for(SearchHit hit:searchHists){
                String name =  (String) hit.getSource().get("name");
                Integer age = (Integer)hit.getSource().get("age");
                System.out.format("name:%s ,age :%d \n",name ,age);
            }
        }
    }
    
}
相關文章
相關標籤/搜索