Elasticsearch与java客户端交互的二种使用
一、原生Elasticsearch
1)导入依赖
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.10.2</version>
</dependency>
2)创建索引
//索引管理
public class IndexManager {private RestHighLevelClient client;@Beforepublic void init(){//创建一个client对象client =new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.92.134",9200)));}/*** 创建索引* @throws Exception*/@Testpublic void creatIndex() throws Exception{//获取索引管理对象IndicesClient indicesClient = client.indices();//两个参数 2、请求选项 使用默认值 配置请求头、主要用于认证//1、创建索引请求对象 参数创建索引名称CreateIndexRequest request = new CreateIndexRequest("hello");CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);//显示结果System.out.println(response);}/*** 创建带有settings的索引* @throws Exception*/@Testpublic void createIndex2() throws Exception{CreateIndexRequest request = new CreateIndexRequest("hello1").settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1));client.indices().create(request,RequestOptions.DEFAULT);}/*** 创建带有settings和mappings的索引* @throws Exception*/@Testpublic void createIndex3() throws Exception{XContentBuilder builder = XContentFactory.jsonBuilder().startObject()//相当于json中的“{”.startObject("properties").startObject("id").field("type","long").endObject()//相当于json中的“}”.startObject("title").field("type","text").field("analyzer","ik_smart").field("store",true).endObject().startObject("content").field("type","text").field("analyzer","ik_smart").field("store",true).endObject().endObject().endObject();CreateIndexRequest request = new CreateIndexRequest("hello3").settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1).build()).mapping(builder);client.indices().create(request,RequestOptions.DEFAULT);}/*** 删除索引* @throws Exception*/@Testpublic void delectIndex() throws Exception{client.indices().delete(new DeleteIndexRequest("hello"),RequestOptions.DEFAULT);}/*** 修改索引中的mappings* @throws Exception*/@Testpublic void putMapping() throws Exception{String mappings = "{\n" +" \"mappings\": {\n" +" \"properties\": {\n" +" \"id\":{\n" +" \"type\": \"long\"\n" +" },\n" +" \"title\":{\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"standard\"\n" +" }\n" +" }\n" +" }\n" +"}\n";PutMappingRequest request = new PutMappingRequest("helle1").source(mappings, XContentType.JSON);client.indices().putMapping(request,RequestOptions.DEFAULT);}
}
3)创建文档
//创建文档
public class DecumentManager {private RestHighLevelClient client;@Beforepublic void init(){//创建一个client对象client =new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.92.134",9200)));}/*** 创建文档* @throws Exception*/@Testpublic void addDecument() throws Exception{String document ="{\"id\":\"1\",\"title\":\"测试文档1\",\"concent\":\"测试文档内容\"}";//创建indexRequest对象,其中包含了索引名称文档id、文档内容IndexRequest indexRequest = new IndexRequest().index("hello1").id("1").source(document, XContentType.JSON);client.index(indexRequest, RequestOptions.DEFAULT);}/*** 更新文档* @throws Exception*/@Testpublic void updateDecument() throws Exception{String document ="{\"id\":\"1\",\"title\":\"测试1文档1\",\"concent\":\"测试文档内容\"}";UpdateRequest request = new UpdateRequest().index("hello1").id("1").doc(document, XContentType.JSON);client.update(request,RequestOptions.DEFAULT);}@Testpublic void deleteDocument() throws Exception{DeleteRequest request = new DeleteRequest("hello1","1");client.delete(request,RequestOptions.DEFAULT);}/*** 查询文档* @throws Exception*/@Testpublic void getDocument() throws Exception{GetRequest getRequest = new GetRequest("hello1","1");client.get(getRequest,RequestOptions.DEFAULT);}/*** 批量添加* @throws Exception*/@Testpublic void bathDocument() throws Exception{String json = "[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"]";JSONArray jsonArray = JSONObject.parseArray(json);BulkRequest request = new BulkRequest();jsonArray.stream().forEach(j->{IndexRequest r = new IndexRequest().index("hello1").id(((JSONObject)j).getString("id")).source(((JSONObject)j).toJSONString(),XContentType.JSON);request.add(r);});client.bulk(request,RequestOptions.DEFAULT);}
}
3)查询索引
//查询索引内容
public class IndexSearch {private RestHighLevelClient client;@Beforepublic void init(){//创建一个client对象client =new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.92.134",9200)));}/*** 查询所有* @throws Exception*/@Testpublic void searchIndex() throws Exception{SearchRequest request = new SearchRequest("hello1").source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//设置查询方式SearchResponse response = client.search(request, RequestOptions.DEFAULT);//从response对象中取出数据SearchHits searchHits =response.getHits();long total = searchHits.getTotalHits().value;System.out.println("查询的总计录数"+total);SearchHit[] searchHits1 = searchHits.getHits();Stream.of(searchHits1).forEach(e->{System.out.println(e);});}/*** 根据title进行查询* @throws Exception*/@Testpublic void termSearch() throws Exception{SearchRequest request = new SearchRequest("hello1").source(new SearchSourceBuilder().query(QueryBuilders.termQuery("title","品")));//设置查询方式SearchResponse response = client.search(request, RequestOptions.DEFAULT);printResult(response);}public void printResult(SearchResponse response){//从response对象中取出数据SearchHits searchHits =response.getHits();long total = searchHits.getTotalHits().value;System.out.println("查询的总计录数"+total);SearchHit[] searchHits1 = searchHits.getHits();Stream.of(searchHits1).forEach(e->{System.out.println(e.getSourceAsString());System.out.println(e.getHighlightFields());});}/*** 设置分页信息* @throws Exception*/@Testpublic void searchPage() throws Exception{SearchRequest request = new SearchRequest("hello1").source(new SearchSourceBuilder()//查询条件.query(QueryBuilders.matchAllQuery())//过滤.postFilter(QueryBuilders.termQuery("title","品"))//高亮显示.highlighter(new HighlightBuilder().field("title").field("content").preTags("<em>").postTags("</em>"))//分页条件.from(0).size(30));SearchResponse response = client.search(request, RequestOptions.DEFAULT);printResult(response);}}
二、使用SpringBoot的Elasticsearch
1)导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
设置对应自己的Elasticsearch的版本号
<elasticsearch.version>7.10.2</elasticsearch.version>
2)配置application配置文件
spring:elasticsearch:rest:uris: xxx.xxx.xxx.xxx:9200//xx是自己的ip地址
3)创建实体类
@Data
@Document(indexName = "blog_1",shards = 5,replicas = 1)
public class Blog {@Id@Field(type = FieldType.Long,store = true)private Long id;@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)private String title;@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)private String content;@Field(type = FieldType.Text,analyzer = "ik_max_word",store = true)private String comment;@Field(type = FieldType.Text,store = true)private String mobile;
}
4)创建索引
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DlmallSearchApplication.class)//因为在测试类给他设置启动
public class RestTemplateTest {@Autowiredprivate ElasticsearchRestTemplate template;/*** 创建名为mytest的索引* @throws Exception*/@Testpublic void createIndex() throws Exception{template.indexOps(IndexCoordinates.of("mytest")).create();}/*** 创建名为mytest的索引并设置mapping信息* @throws Exception*/@Testpublic void putMapping(){Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);template.indexOps(IndexCoordinates.of("mytest")).putMapping(mapping);}/*** 根据实体类对象创建mapping*/@Testpublic void createIndexWithMapping(){// template.indexOps(Blog.class).create();Document mapping = template.indexOps(IndexCoordinates.of("mytest")).createMapping(Blog.class);template.indexOps(Blog.class).putMapping(mapping);}/*** 删除索引*/@Testpublic void deleteIndex(){template.indexOps(IndexCoordinates.of("hello1")).delete();}}
5)创建文档和查询文档
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BlogRepositoryTest {@Autowiredprivate BlogRepository blogRepository;/*** 根据实体类blog创建相对应得文档信息*/@Testpublic void addDocument(){Blog blog = new Blog();blog.setId(1l);blog.setTitle("测试1");blog.setContent("neirong1");blog.setComment("内容");blog.setMobile("1111111111");blogRepository.save(blog);}/*** 更新文档*/@Testpublic void updateDocument(){Optional<Blog> optional = blogRepository.findById(1l);if (optional.isPresent()){Blog blog = optional.get();blog.setTitle("hello word");blogRepository.save(blog);}}/*** 删除文档*/@Testpublic void deleteDocument(){blogRepository.deleteById(1l);}/*** 根据id查询文档和查询全部进行分页*/@Testpublic void getById(){Optional<Blog> optional = blogRepository.findById(1l);Blog blog = optional.get();System.out.println(blog);//分页Iterable<Blog> all = blogRepository.findAll(PageRequest.of(1, 10));all.forEach(e->{System.out.println(e);});}
}
6)使用批量
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DlmallSearchApplication.class)
public class BulkTest {@Autowiredprivate ElasticsearchRestTemplate template;/*** 批量添加索引文档内容*/@Testpublic void bulkBlog(){JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":4, \"title\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"content\":\"柳子戏《江姐》进入联排阶段,月底将与济南观众见面\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"]");List<IndexQuery> list = json.stream().map(query -> {IndexQuery indexQuery = new IndexQuery();indexQuery.setId(((JSONObject) query).getString("id"));indexQuery.setSource(((JSONObject) query).toJSONString());return indexQuery;}).collect(Collectors.toList());template.bulkIndex(list, IndexCoordinates.of("mytest"));}/*** 批量添加索引文档内容(使用实体类对象)*/@Testpublic void bulkSaveBlog(){JSONArray json = JSON.parseArray("[{\"id\":1, \"title\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"content\":\"帮日本核废水“出招”?知名男艺人迷之操作让人看呆了..\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":2, \"title\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"content\":\"《奔跑吧9》4月23日开播,沙溢、蔡徐坤等回归\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"{\"id\":3, \"title\":\"桐梓:九坝这群人田间指导忙\", \"content\":\"桐梓:九坝这群人田间指导忙\", \"comment\":\"娱乐\", \"mobile\":\"13900112233\"}\n" +"]");List<Blog> list = json.stream().map(query -> {JSONObject jsonObject = (JSONObject) query;Blog blog = jsonObject.toJavaObject(Blog.class);return blog;}).collect(Collectors.toList());template.save(list);}
}
Elasticsearch与java客户端交互的二种使用相关推荐
- 【Elasticsearch】java 客户端 获取 termvectors 词频 统计
1.概述 2.获取单条index的词频 elasticsearch的termvectors包括了term的位置.词频等信息.这些信息用于相应的数据统计或开发其他功能,本文介绍termvecters如何 ...
- Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式…)介绍(转)
[-] 一普通同步方式 二事务方式Transactions 三管道Pipelining 四管道中调用事务 五分布式直连同步调用 六分布式直连异步调用 七分布式连接池同步调用 八分布式连接池异步调用 九 ...
- Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式…)介绍--转载
原文地址:http://www.blogways.net/blog/2013/06/02/jedis-demo.html redis是一个著名的key-value存储系统,而作为其官方推荐的java版 ...
- Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式)介绍
一.普通同步方式 二.事务方式(Transactions) 三.管道(Pipelining) 四.管道中调用事务 五.分布式直连同步调用 六.分布式直连异步调用 七.分布式连接池同步调用 八.分布式连 ...
- java redis管道_Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式)介绍
jedis是一个著名的key-value存储系统,而作为其官方推荐的java版客户端jedis也非常强大和稳定,支持事务.管道及有jedis自身实现的分布式. 在这里对jedis关于事务.管道和分布式 ...
- 干货 | Elasticsearch Java 客户端演进历史和选型指南
1.Elasticsearch java 客户端为什么要选型? Elasticsearch 官方提供了很多版本的 Java 客户端,包含但不限于: Transport 客户端 Java REST 客户 ...
- 来聊一聊 ElasticSearch 最新版的 Java 客户端
可能不少小伙伴都注意到了,从 ElasticSearch7.17 这个版本开始,原先的 Java 高级客户端 Java High Level REST Client 废弃了,不支持了.老实说,Elas ...
- ElasticSearch集群安装及Java客户端使用
ElasticSearch集群安装及Java客户端使用 1.传统模式安装 1.1 ElasticSearch安装 下载Es安装包 ElasticSearch的官方地址:https://www.elas ...
- Java代码设计模式讲解二十三种设计模式
设计模式 文章目录 设计模式 一.创造型设计模式 1.1 单例模式 1.1.1 饿汉式单例模式 1.1.2 懒汉式单例模式 (1)线程不安全的情况 (2)线程安全的情况 1. 实例化的方法上加sync ...
最新文章
- 李宏毅线性代数笔记4:向量
- 你见过动物是怎么笑的吗?赶紧来看看【组图】
- 结对-英文词频分析-开发环境搭建过程
- jboss url路径_在JBoss的服务器端正确解码URL参数
- 四个人过桥的题目_云南的几种“勾魂”特产,舌尖上的美味,让人回味无穷,你吃过吗...
- 推荐一些数据挖掘和生信友好的SCI!
- CodeIgniter笔记3
- 每日一题 2020.05.12
- jenkins手把手教你从入门到放弃02-jenkins在Windows系统安装与配置(详解)
- 动态时间规整算法_如何使用动态时间规整算法进行语音识别
- python的spider如何让鼠标不_【专题教学】python wooyun爬虫模拟鼠标等
- java过滤器的作用_javaweb过滤器的作用,过滤器filter的作用是什么?
- 设计模式之建造者和原型模式
- Rabbitmq 安全账号管理方案
- 错误使用empty()函数
- hive中的绣花模型_跨界媒介的碰撞:蜂巢+刺绣 | Ava Roth 「艺术访谈」
- Android万能遥控菜单选择添加,将小米米家万能遥控器添加到Home Assistant
- 【实战记录】使用阿里云的OSS云存储,上传与删除图片及遇到的问题
- 计算机windows7连接打印机
- Windows记事本
热门文章
- UI自动化测试工具探索:Airtest
- 变量循环重新标号法求对称正定矩阵逆矩阵
- 如何学习一个开源项目源码
- python项目分析报告_实战 | Python自动生成PPT分析报告
- 【天光学术】旅游管理论文:大连金石滩旅游餐饮文化资源开发对策研究
- 2008大连国际沙滩文化节将在金石滩举行
- wegame启动cf蓝屏_Wegame蓝屏怎么解决-解决wegame运行蓝屏、游戏蓝屏的方法 - 河东软件园...
- 如何学编程,我的一些学习感悟
- 不卸载升级cmake
- “大湾区杯”金融数学建模赛后闲谈