首頁 > 網際網路

elasticsearch學習四、JAVA呼叫

2019-12-10 11:22:21

在java中如何呼叫ElasticSearch,步驟同‘IK中文分詞的使用’中的步驟

1

建立用戶端連線

叢集名稱預設為elasticsearch,沒有修改過無需setting可以建立連線:

Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("172.20.0.196", 9300));

如果修改過叢集的名稱:

Settings settings = ImmutableSettings.settingsBuilder()

.put("cluster.name", "elasticsearch_01").build();

Client client = new TransportClient(settings)       

.addTransportAddress(new InetSocketTransportAddress("172.20.0.196", 9300));


2

建立索引

public void createIndex(String index){

client.admin().indices().create(new CreateIndexRequest(index)).actionGet();  

        // waitForYellow  

        client.admin().cluster().health(new ClusterHealthRequest(index)

        .waitForYellowStatus())

        .actionGet();

}


3

建立mapping,和curl中完全對應,同樣指定分析器為ik

public void createMapping(String index,String type) throws IOException{

XContentBuilder builder = XContentFactory.jsonBuilder()

.startObject()

.startObject(type)

.startObject("_all")

.field("indexAnalyzer", "ik")

.field("searchAnalyzer", "ik")

.field("term_vector", "no")

.field("store", "false")

.endObject()

.startObject("properties")

.startObject("content")

.field("type", "string")

.field("store", "no")

.field("term_vector", "with_positions_offsets")

.field("indexAnalyzer", "ik")

.field("searchAnalyzer", "ik")

.field("include_in_all", "true")

.field("boost", 9)

.endObject()

.endObject()

.endObject()

.endObject();

PutMappingRequest mapping = Requests.putMappingRequest(index).type(type).source(builder);

client.admin().indices().putMapping(mapping).actionGet();

}


4

索引一些資料,建立成功isCreated()返回true

public void createData(String index,String type){

List<String> jsondata = ElasticsearchTest.getInitJsonData();

        for(int i=0; i<jsondata.size(); i++){

        IndexResponse indexResp = client.prepareIndex()

        .setIndex(index).setType(type).setId(i+1+"")

        .setSource(jsondata.get(i)).execute().actionGet();

        boolean isCreated = indexResp.isCreated();

        System.out.println("是否成功建立資料isCreated:"+isCreated);

        }

}


5

查詢資料方法

public void queryData(String index,String type){

QueryBuilder queryBuilder =  QueryBuilders.termQuery("content", "中國");

        SearchResponse searchResponse = client.prepareSearch(index).setTypes(type)

                .setQuery(queryBuilder)

                .execute()

                .actionGet();

        SearchHits hits = searchResponse.getHits();

        System.out.println("查詢到記錄數:" + hits.getTotalHits());

        SearchHit[] searchHists = hits.getHits();

        for(SearchHit sh : searchHists){

        System.out.println("content:"+sh.getSource().get("content"));

        }

}


6

在main方法中呼叫

建立索引、mapping、資料


7

按條件查詢,顯示查詢結果。


8

同時可以開啟head介面檢視下執行效果



IT145.com E-mail:sddin#qq.com