重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要讲解了“怎么使用ES客户端来操作搜索引新”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用ES客户端来操作搜索引新”吧!
专注于为中小企业提供成都网站设计、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业牟平免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了超过千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
1 导入需要的pom
org.elasticsearch elasticsearch 7.3.0 org.elasticsearch.client transport 7.3.0 org.apache.logging.log4j log4j-core 2.11.1 com.fasterxml.jackson.core jackson-databind 2.9.9.3 com.fasterxml.jackson.core jackson-annotations 2.9.9
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()); Iteratoriterator = searchHits.iterator(); while(iterator.hasNext()) { SearchHit hit = iterator.next(); System.out.println(hit.getSourceAsString()); System.out.println("------获取文档属性------"); Map 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(""); //设置前缀 highlightBuilder.postTags("");//设置后缀 //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 iterator = searchHits.iterator(); while(iterator.hasNext()) { SearchHit hit = iterator.next(); System.out.println(hit.getSourceAsString()); System.out.println("------获取文档属性------"); Map map = hit.getSourceAsMap(); System.out.println(map.get("content")); System.out.println("------获取高亮显示的数据------"); Map 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客户端来操作搜索引新这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!