这篇文章主要讲解了“怎么使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。