elasticsearch 5.5.0 java操作(新增索引、分頁搜尋)
阿新 • • 發佈:2019-02-01
網上資源比較亂、比較雜,稍微總結一下,幫助大家避免像我一樣走彎路…………
————————————————————————————————————
首先引入maven依賴:
<!--elasticsearch--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.5.0</version> </dependency>
公共client:獲取ES的client,任何操作都需要此client(類似httpclient吧,傳送請求操作):
提醒:使用完畢記得關閉,呼叫:client.close();// 設定叢集名稱cluster.name: Settings settings = Settings.builder().put("cluster.name", "betawoo_es").build(); //特別注意,java操作埠為:9300 Client client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("139.116.196.10"), 9300));
1、新建索引
//json字串,也可以直接傳Map String json = "{\"title\":\"我從windows建立\",\"label\":[\"美式沙發\"],\"create_date\":\"2017-11-1 15:41:01\"}"; IndexResponse response = client.prepareIndex("index_名稱", "type_名稱").setId("0").setSource(json).execute().actionGet(); // Index name String _index = response.getIndex(); // Type name String _type = response.getType(); // Document ID (generated or not) String _id = response.getId(); // Version long _version = response.getVersion(); System.out.println("-------:"+_id+"建立成功!");
2、刪除索引(根據id刪除)
DeleteResponse deleteresponse = client.prepareDelete("index_名稱", "type_名稱","9db3f12721624f6a888e0c62181ffe8a")
.execute()
.actionGet();
System.out.println(deleteresponse.getVersion());
3、分頁搜尋
QueryBuilder包路徑:importorg.elasticsearch.index.query.QueryBuilder;
//搜尋匹配內容,等同:curl -X GET http://localhost:9200/test/kind/_search?pretty -d '{"query" : {"match" : {"label" : "映享優選"}}}'
QueryBuilder matchQuery = QueryBuilders.matchQuery("label", "映享優選");
SearchResponse response = client.prepareSearch("portal").setTypes("product")//設定索引和型別
.setQuery(matchQuery).setFrom(0).setSize(60)//設定分頁引數(獲取1-60條,0開始)類似mysql limit分頁
.execute().actionGet();
//獲取查詢結果集
SearchHits searchHits = response.getHits();
System.out.println("共搜到:"+searchHits.getTotalHits()+"條結果!");
//遍歷結果
for(SearchHit hit:searchHits){
System.out.println("String方式列印文件搜尋內容:");
System.out.println(hit.getSourceAsString());
// System.out.println(hit.getId());
}