您好,登錄后才能下訂單哦!
這篇文章主要講解了“怎么使用ES客戶端來操作搜索引新”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么使用ES客戶端來操作搜索引新”吧!
1 導入需要的pom
<dependencies> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.3.0</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>7.3.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.1</version> </dependency> <!-- 把對象轉換成json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.9</version> </dependency> </dependencies>
2 編寫方法
package com.shi.es; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.transport.client.PreBuiltTransportClient; import com.fasterxml.jackson.databind.ObjectMapper; /** * ES客戶端類 * * @author shiye * */ public class ElasticSearchClient { /** * 創建索引 * @throws Exception */ public void createIndex() throws Exception { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); // 3 使用client創建一個索引庫 client.admin().indices().prepareCreate("index_client").get();// 執行操作 System.out.println("index_client 索引設置成功..."); // 4 關閉client對象 client.close(); } /** * 設置mapping信息 * @throws IOException */ public void setMappings() throws IOException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); // { // "properties": { // "content": { // "type": "text", // "analyzer": "ik_max_word", // "search_analyzer": "ik_max_word" // } // } // } XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .startObject("properties") .startObject("content") .field("type", "text") .field("analyzer","ik_max_word") .field("search_analyzer","ik_max_word") .endObject() .endObject() .endObject(); System.out.println(builder.toString()); //使用client把mapping信息設置到索引庫中 client.admin().indices() .preparePutMapping("index_client") //設置要做映射的索引 .setType("content")//設置要做映射的type .setSource(builder)//mapping信息 .get();//執行操作 System.out.println("mapping設置成功..."); //管理客戶端 client.close(); } /** * 添加文檔 方式一 * @throws IOException */ public void setAddDOC1() throws IOException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .field("content","美國留給伊拉克的是個爛攤子嗎") .endObject(); System.out.println(builder.isPrettyPrint()); //把文檔對象添加到索引庫 client.prepareIndex() .setIndex("index_client") //設置索引名稱 .setType("content") //設置type .setId("1") //設置文檔的id,如果不設置的話自動生成一個id .setSource(builder) //設置文檔信息 .get(); //執行操作 System.out.println("文檔添加成功..."); //關閉客戶端 client.close(); } /** * 添加文檔 方式二 * @throws IOException */ public void setAddDOC2() throws IOException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); //創建對象 Content content = new Content(); content.setContent("公安部:各地校車將享最高路權"); ObjectMapper objectMapper = new ObjectMapper(); String jsonDocument = objectMapper.writeValueAsString(content); System.out.println(jsonDocument); //使用client對象把文檔寫入索引庫 client.prepareIndex("index_client", "content") .setSource(jsonDocument,XContentType.JSON) .get(); System.out.println("文檔添加成功..."); //關閉客戶端 client.close(); } }
package com.shi.es; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Iterator; import java.util.Map; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.transport.TransportAddress; 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.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.transport.client.PreBuiltTransportClient; public class ESQueryClient { /** * 簡單的執行查詢對象 * @param client * @param builder */ private void search(TransportClient client , QueryBuilder builder) { //4 執行查詢 SearchResponse searchResponse = client.prepareSearch("index_client") .setTypes("content") .setQuery(builder) .setFrom(0) //起始行數 .setSize(5) //每一頁顯示的數量 .get(); //5 取查詢結果 SearchHits searchHits = searchResponse.getHits(); System.out.println("查詢到的總的結果數 = " + searchHits.getTotalHits()); Iterator<SearchHit> iterator = searchHits.iterator(); while(iterator.hasNext()) { SearchHit hit = iterator.next(); System.out.println(hit.getSourceAsString()); System.out.println("------獲取文檔屬性------"); Map<String, Object> map = hit.getSourceAsMap(); System.out.println(map.get("content")); } } /** * 設置高亮顯示的查詢 * @param client * @param builder * @param hightFiled */ private void search(TransportClient client , QueryBuilder builder, String hightFiled) { HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field(hightFiled); //設置需要高亮顯示的域 highlightBuilder.preTags("<em>"); //設置前綴 highlightBuilder.postTags("</em>");//設置后綴 //4 執行查詢 SearchResponse searchResponse = client.prepareSearch("index_client") .setTypes("content") .setQuery(builder) .setFrom(0) //起始行數 .setSize(5) //每一頁顯示的數量 .highlighter(highlightBuilder)//設置高亮顯示 .get(); //5 取查詢結果 SearchHits searchHits = searchResponse.getHits(); System.out.println("查詢到的總的結果數 = " + searchHits.getTotalHits()); Iterator<SearchHit> iterator = searchHits.iterator(); while(iterator.hasNext()) { SearchHit hit = iterator.next(); System.out.println(hit.getSourceAsString()); System.out.println("------獲取文檔屬性------"); Map<String, Object> map = hit.getSourceAsMap(); System.out.println(map.get("content")); System.out.println("------獲取高亮顯示的數據------"); Map<String, HighlightField> highlightFields = hit.getHighlightFields(); HighlightField field = highlightFields.get(hightFiled); Text[] fragments = field.getFragments(); if(fragments != null) { System.out.println(fragments[0]); } } } /** * 通過id來查詢 * @throws UnknownHostException */ public void queryById() throws UnknownHostException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); //3 創建一個查詢對象 QueryBuilder builder = QueryBuilders.idsQuery().addIds("1","2","3"); search(client,builder);//執行查詢 } /** * 通過Term來查詢 * @throws UnknownHostException */ public void queryByTerm() throws UnknownHostException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); //3 創建一個查詢對象 QueryBuilder builder = QueryBuilders.spanTermQuery("content", "伊拉克"); // search(client,builder);//執行查詢 search(client,builder,"content");//執行高亮查詢 } /** * 通過StringQuery來查詢 * 先對需要查詢的字符串進行分詞,在查詢 * @throws UnknownHostException */ public void queryByQueryString() throws UnknownHostException { // 1 創建一個Settings對象,相當于一個配置信息,主要配置集群中的名稱 Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build(); // 2 創建一個客戶端client對象 (單機版的暫時沒問題,集群的有問題) TransportClient client = new PreBuiltTransportClient(Settings.EMPTY); client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); //3 創建一個查詢對象 QueryBuilder builder = QueryBuilders.queryStringQuery("無人駕駛校車").defaultField("content"); search(client,builder);//執行查詢 } }
3 測試
package com.shi.es; public class ClientTest { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //創建 // ElasticSearchClient esClient = new ElasticSearchClient(); // esClient.createIndex(); //創建索引庫 // esClient.setMappings();//設置mapping信息 // esClient.setAddDOC1();//添加文檔 方式1 // esClient.setAddDOC2();//添加文檔 方式2 //查詢 ESQueryClient client = new ESQueryClient(); // client.queryById(); client.queryByTerm(); // client.queryByQueryString(); } }
感謝各位的閱讀,以上就是“怎么使用ES客戶端來操作搜索引新”的內容了,經過本文的學習后,相信大家對怎么使用ES客戶端來操作搜索引新這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。