elasitsearch5.6.2 (java API)
阿新 • • 發佈:2020-12-14
今天第一次使用版本5.X, 和2.X 有些區別(整體使用上區別不是很大) :
整理下:
package com.sea.es; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Requests; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.junit.Before; import org.junit.Test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Iterator; import java.util.Map;/** * @PACKAGE : com.sea.es * @Author : Sea * @Date : 12/14/20 12:55 PM * @Desc : **/ public class ESTest { public static String CLUSTER_NAME = "es-cluster";//Elasticsearch叢集名稱 public static String HOST_IP = "192.168.18.129";//Elasticsearch叢集節點 public static int TCP_PORT = 9300;//Elasticsearch節點TCP通訊埠private volatile static TransportClient client;//客戶端物件,用於連線到Elasticsearch叢集 public static TransportClient getSingleTransportClient() { Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).build(); try { if(client == null) { synchronized(TransportClient.class) { client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT)); } } } catch (UnknownHostException e) { e.printStackTrace(); } return client; } @Before public void init(){ TransportClient client = getSingleTransportClient(); } @Test public void testName() throws Exception { // GetResponse getResponse = client.prepareGet("books", "IT", "1").get(); // System.out.println(getResponse.getSourceAsString()); client.admin().indices().prepareCreate("shan").get(); } /** * 使用json來建立文件、索引、自動建立對映 */ @Test public void createDoc_1() { // json資料 String source = "{" + "\"id\":\"3\"," + "\"title\":\"ElasticSearch是一個基於Lucene的搜尋伺服器\"," + "\"content\":\"它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面\"" + "}"; // 開始建立文件 // .execute().actionGet() == .get() IndexResponse indexResponse = client.prepareIndex("blog01", "article", "3").setSource(source, XContentType.JSON).get(); // 獲取響應資訊 System.out.println("索引:" + indexResponse.getIndex()); System.out.println("型別:" + indexResponse.getType()); System.out.println("ID:" + indexResponse.getId()); System.out.println("版本:" + indexResponse.getVersion()); System.out.println("是否建立成功:" + indexResponse.status()); client.close(); } /** * 使用map來建立文件 */ @Test public void createDoc_2() { // map格式的資料 Map<String, Object> source = new HashMap<>(); source.put("id", "2"); source.put("title", "我們建立一個網站或應用程式"); source.put("content", "但是想要完成搜尋工作的建立是非常困難的"); // 建立文件 IndexResponse indexResponse = client.prepareIndex("blog01", "article", "2").setSource(source).get(); // 獲取響應資訊 System.out.println("索引:" + indexResponse.getIndex()); System.out.println("型別:" + indexResponse.getType()); System.out.println("ID:" + indexResponse.getId()); System.out.println("版本:" + indexResponse.getVersion()); // System.out.println("是否建立成功:" + indexResponse.isCreated()); client.close(); } /** * 使用es的幫助類來建立文件 */ @Test public void createDoc_3() throws Exception { XContentBuilder sourse = XContentFactory.jsonBuilder() .startObject() .field("id", "3") .field("title", "Elasticsearch是用Java開發的") .field("content", "並作為Apache許可條款下的開放原始碼釋出,是當前流行的企業級搜尋引擎") .endObject(); IndexResponse indexResponse = client.prepareIndex("blog01", "article", "3").setSource(sourse).get(); // 獲取響應資訊 System.out.println("索引:" + indexResponse.getIndex()); System.out.println("型別:" + indexResponse.getType()); System.out.println("ID:" + indexResponse.getId()); System.out.println("版本:" + indexResponse.getVersion()); System.out.println("是否建立成功:" + indexResponse.getShardInfo()); client.close(); } /** * 搜尋文件資料,搜尋單個索引 */ @Test public void testGetData_1() { GetResponse getResponse = client.prepareGet("blog01", "article", "2").get(); System.out.println(getResponse.getSourceAsString()); client.close(); } /** * 搜尋文件資料,搜尋多個索引 */ @Test public void testGetData_2() { MultiGetResponse itemResponses = client.prepareMultiGet() // .add("blog01", "article", "1") .add("blog01", "article", "2", "3","1") .get(); // 遍歷獲取的資料 for (MultiGetItemResponse item : itemResponses) { GetResponse response = item.getResponse(); System.out.println(response.getSourceAsString()); } client.close(); } /** * 更新文件資料 */ @Test public void testUpdate_1() throws Exception { UpdateRequest request = new UpdateRequest(); request.index("blog01"); // 指定更新的index request.type("article"); // 指定更新的type request.id("1"); // 指定更新的id request.doc(XContentFactory.jsonBuilder() .startObject() .field("id", "1") .field("title", "更新:ElasticSearch是一個基於Lucene的搜尋伺服器") .field("content", "更新:它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面") .endObject()); // 開始更新 UpdateResponse updateResponse = client.update(request).get(); // 獲取響應資訊 System.out.println("索引:" + updateResponse.getIndex()); System.out.println("型別:" + updateResponse.getType()); System.out.println("ID:" + updateResponse.getId()); System.out.println("版本:" + updateResponse.getVersion()); // System.out.println("是否建立成功:" + updateResponse.isCreated()); client.close(); } /** * 更新文件資料 */ @Test public void testUpdate_2() throws Exception { // 開始更新 UpdateResponse updateResponse = client.update(new UpdateRequest("blog01", "article", "2") .doc(XContentFactory.jsonBuilder().startObject() .field("id", "2") .field("title", "更新:我們建立一個網站或應用程式") .field("content", "更新:但是想要完成搜尋工作的建立是非常困難的") .field("sea", "更新:sea sea sea sea") //可以新增欄位 .endObject() )).get(); // 獲取響應資訊 System.out.println("索引:" + updateResponse.getIndex()); System.out.println("型別:" + updateResponse.getType()); System.out.println("ID:" + updateResponse.getId()); System.out.println("版本:" + updateResponse.getVersion()); // System.out.println("是否建立成功:" + updateResponse.isCreated()); client.close(); } /** * 更新文件資料,設定查詢的條件,如果查詢不到資料,就新增資料 */ @Test public void testUpdate_3() throws Exception { IndexRequest indexRequest = new IndexRequest("blog", "article", "4") .source(XContentFactory.jsonBuilder() .startObject() .field("id", "4") .field("title", "一個基於Lucene的搜尋伺服器") .field("content", "它提供了一個分散式多使用者能力的全文搜尋引擎,基於RESTful web介面") .endObject()); // 設定更新的資料,如果查不到,則更新 UpdateRequest updateRequest = new UpdateRequest("blog01", "article", "4") .doc(XContentFactory.jsonBuilder() .startObject() .field("title", "我們建立一個網站或應用程式,並要新增搜尋功能") .endObject()) .upsert(indexRequest); UpdateResponse updateResponse = client.update(updateRequest).get(); // 獲取響應資訊 System.out.println("索引:" + updateResponse.getIndex()); System.out.println("型別:" + updateResponse.getType()); System.out.println("ID:" + updateResponse.getId()); System.out.println("版本:" + updateResponse.getVersion()); // System.out.println("是否建立成功:" + updateResponse.isCreated()); client.close(); } /** * 刪除資料 */ @Test public void testDel() { DeleteResponse deleteResponse = client.prepareDelete("blog01", "article", "4").get(); // System.out.println("是否返回結果:" + deleteResponse.isFound()); System.out.println("是否返回結果:" + deleteResponse.getShardInfo()); client.close(); } /** * 查詢文件資料 */ @Test public void testSearch() { // QueryString查詢 SearchResponse searchResponse = client.prepareSearch("blog01") .setTypes("article") .setQuery(QueryBuilders.queryStringQuery("引擎")) // 發現在查詢是隻是依據第一個字來查詢 .get(); // 獲取結果集物件,獲取命中次數 SearchHits hits = searchResponse.getHits(); System.out.println("查詢的結果資料有" + hits.getTotalHits() + "條"); // 遍歷每條資料 Iterator<SearchHit> it = hits.iterator(); while (it.hasNext()) { SearchHit searchHit = it.next(); // 列印整條資訊 System.out.println(searchHit.getSourceAsString()); // 獲取欄位資訊 // System.out.println("id:" + searchHit.getSource().get("id")); // System.out.println("title:" + searchHit.getSource().get("title")); // System.out.println("content" + searchHit.getSource().get("content")); System.out.println("id:" + searchHit.getFields().get("id")); System.out.println("title:" + searchHit.getFields().get("title")); System.out.println("content" + searchHit.getFields().get("content")); } client.close(); } /** * 建立索引 */ @Test public void testCreateIndex() { // 建立index client.admin().indices().prepareCreate("blog01").get(); // 刪除index // client.admin().indices().prepareDelete("blog01").get(); } /** * 建立一個帶有對映的索引 */ @Test public void testCreateIndexAndMapping() throws Exception { final XContentBuilder mappingBuilder = XContentFactory.jsonBuilder() .startObject() .startObject("article") .startObject("properties") .startObject("id") .field("type", "integer").field("store", "yes") .endObject() .startObject("title") .field("type", "string").field("store", "yes").field("analyzer", "ik_max_word") .endObject() .startObject("content") .field("type", "string").field("store", "yes").field("analyzer", "ik_max_word") .endObject() .endObject() .endObject() .endObject(); PutMappingRequest request = Requests.putMappingRequest("blog01") .type("article") .source(mappingBuilder); client.admin().indices().putMapping(request).get(); client.close(); } /** * 各種查詢 */ @Test public void testSearchMapping() { // queryString查詢 // SearchResponse searchResponse = client.prepareSearch("blog01") // .setTypes("article") // .setQuery(QueryBuilders.queryStringQuery("引擎")) // .get(); // 詞條查詢 // 它僅匹配在給定的欄位中去查詢,而且是查詢含有該詞條的內容 // SearchResponse searchResponse = client.prepareSearch("blog01") // .setTypes("article") // .setQuery(QueryBuilders.termQuery("content", "引擎")) // .get(); // 萬用字元查詢 // SearchResponse searchResponse = client.prepareSearch("blog01") // .setTypes("article") // .setQuery(QueryBuilders.wildcardQuery("content", "接?")) // .get(); // 模糊查詢 // SearchResponse searchResponse = client.prepareSearch("blog01") // .setTypes("article") // .setQuery(QueryBuilders.fuzzyQuery("title", "Lucena")) // .get(); // 解析字串查詢,指定欄位 // SearchResponse searchResponse = client.prepareSearch("blog01") // .setTypes("article") // .setQuery(QueryBuilders.queryStringQuery("介面").field("content").field("title")) // .get(); // 欄位匹配查詢 // SearchResponse searchResponse = client.prepareSearch("blog01").setTypes("article") // .setQuery(QueryBuilders.matchPhrasePrefixQuery("title", "服 ").slop(1)) // .get(); // 範圍查詢 SearchResponse searchResponse = client.prepareSearch("blog01").setTypes("article") .setQuery(QueryBuilders.rangeQuery("id") //.from("它提供").to("引擎").includeLower(true).includeUpper(true)) .gt(1).lt(4)) .get(); this.getHits(searchResponse); client.close(); } /** * 檢視響應資訊方法 */ public void getHits(SearchResponse searchResponse) { // 獲取結果集物件,獲取命中次數 SearchHits hits = searchResponse.getHits(); System.out.println("查詢的結果資料有" + hits.getTotalHits() + "條"); // 遍歷每條資料 Iterator<SearchHit> it = hits.iterator(); while (it.hasNext()) { SearchHit searchHit = it.next(); // 列印整條資訊 System.out.println(searchHit.getSourceAsString()); // 獲取欄位資訊 System.out.println("id:" + searchHit.getFields().get("id")); System.out.println("title:" + searchHit.getFields().get("title")); System.out.println("content" + searchHit.getFields().get("content")); } } }