java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索
1.pom 导入jar
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.17.4</version>
</dependency>
ElasticSerarchService.java 根据歌名搜索
package com.redis.demo; import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; public class ElasticSerarchService {
public static void main(String[] args) throws Exception{
RestHighLevelClient client = getClient(); //查询
//默认ID
GetRequest getRequest = new GetRequest("songs_v2", "_doc", "5EnOMYEBLnSF9_D_wh38");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println("根据ID查询="+getResponse.getSourceAsString()); SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("songs_v2"); //查询所有记录
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
// System.out.println("searchSourceBuilder="+ JSON.toJSONString(searchSourceBuilder));
//searchSourceBuilder={"query":{"match_all":{"boost":1.0}}}
System.out.println("searchSourceBuilder="+ searchSourceBuilder); //根据条件查询 歌名
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.query(QueryBuilders.termQuery("songName", "tianyi"));
// sourceBuilder.from(0);
// sourceBuilder.size(5);
// sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// searchRequest.source(sourceBuilder);
//
// //{"from":0,"size":5,"timeout":"60s","query":{"term":{"songName":{"value":"tianyi","boost":1.0}}}}
// //打印输出,而不是JSON.toJSONString方式来输出
// System.out.println("sourceBuilder="+ sourceBuilder); System.out.println("searchRequest="+ JSON.toJSONString(searchRequest));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); // RestStatus status = searchResponse.status();
// TimeValue took = searchResponse.getTook();
// Boolean terminatedEarly = searchResponse.isTerminatedEarly();
// boolean timedOut = searchResponse.isTimedOut();
//
// int totalShards = searchResponse.getTotalShards();
// int successfulShards = searchResponse.getSuccessfulShards();
// int failedShards = searchResponse.getFailedShards();
// for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
// // failures should be handled here
// System.out.println("failures should be handled here");
// } SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
// do something with the SearchHit String sourceAsString = hit.getSourceAsString();
// Map<String, Object> sourceAsMap = hit.getSourceAsMap();
// String documentTitle = (String) sourceAsMap.get("title");
// List<Object> users = (List<Object>)) sourceAsMap.get("user");
// Map<String, Object> innerObject =
// (Map<String, Object>) sourceAsMap.get("innerObject");
System.out.println("查询结果sourceAsString=" + sourceAsString);
} close(client); } private static void close(RestHighLevelClient client) throws IOException {
client.close();
} private static RestHighLevelClient getClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
}
IndexTest.java 创建索引
package com.redis.demo.elasticserach; import com.redis.demo.ElasticSerarchService;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Cancellable;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType; import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; public class IndexTest {
private static RestHighLevelClient getClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
} private static void close(RestHighLevelClient client) throws IOException {
client.close();
} public static void main(String[] args) throws Exception{
IndexRequest request = new IndexRequest("posts");
request.id("1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
// request.routing("routing");
// request.timeout(TimeValue.timeValueSeconds(1));
// request.timeout("1s"); RestHighLevelClient client = getClient();
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println("indexResponse1="+indexResponse.getResult()); //无法重复创建索引
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest indexRequest = new IndexRequest("posts")
.id("2").source(jsonMap); indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("indexResponse2="+indexResponse.getResult()); XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("user", "kimchy");
builder.timeField("postDate", new Date());
builder.field("message", "trying out Elasticsearch");
}
builder.endObject();
IndexRequest indexRequest3 = new IndexRequest("posts")
.id("3").source(builder);
indexResponse = client.index(indexRequest3, RequestOptions.DEFAULT);
System.out.println("indexResponse3="+indexResponse.getResult());
/**
* if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
*
* } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
*
* }
*/ IndexRequest indexRequest4 = new IndexRequest("posts")
.id("4")
.source("user", "kimchy",
"postDate", new Date(),
"message", "trying out Elasticsearch"); ActionListener listener = new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
System.out.println("异步通知结果result =" + indexResponse.getResult());
System.out.println("异步通知结果id =" + indexResponse.getId()); } @Override
public void onFailure(Exception e) {
System.out.println("异步通知结果异常啦" + e.getMessage());
}
}; //异步方式
Cancellable cancellable = client.indexAsync(indexRequest4, RequestOptions.DEFAULT, listener); //处理异常的情况,id重复 主键冲突
IndexRequest request5 = new IndexRequest("posts")
.id("1")
.source("field", "value")
.setIfSeqNo(10L)
.setIfPrimaryTerm(20);
try {
IndexResponse response = client.index(request5, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
if (e.status() == RestStatus.CONFLICT) {
System.out.println("5主键冲突啦" + e.getMessage()); }
} IndexRequest request6 = new IndexRequest("posts")
.id("1")
.source("field", "value")
.opType(DocWriteRequest.OpType.CREATE);
try {
IndexResponse response = client.index(request6, RequestOptions.DEFAULT);
} catch(ElasticsearchException e) {
if (e.status() == RestStatus.CONFLICT) {
System.out.println("6主键冲突啦" + e.getMessage());
}
} //关闭
close(client); }
}
GetRequestTest.java 根据ID查询
package com.redis.demo.elasticserach; import com.redis.demo.ElasticSerarchService;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus; import java.io.IOException;
import java.util.Map; public class GetRequestTest {
private static RestHighLevelClient getClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
} private static void close(RestHighLevelClient client) throws IOException {
client.close();
} public static void main(String[] args) throws Exception{
GetRequest getRequest = new GetRequest(
"posts",
"100"); try {
RestHighLevelClient client = getClient();
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
String index = getResponse.getIndex();
String id = getResponse.getId();
if (getResponse.isExists()) {
long version = getResponse.getVersion();
String sourceAsString = getResponse.getSourceAsString();
// Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
// byte[] sourceAsBytes = getResponse.getSourceAsBytes();
System.out.println("sourceAsString=" + sourceAsString);
} else {
System.out.println("getResponse不存在");
} //关闭
close(client); } catch (ElasticsearchException e) {
System.out.println("异常"+e.status());
if (e.status() == RestStatus.NOT_FOUND) {
System.out.println("未找到"+e.status());
}
}
}
}
java elasticsearch-rest-high-level-client 根据歌名搜索,创建索引,根据索引ID搜索的更多相关文章
- springboot整合elasticsearch(基于es7.2和官方high level client)
前言 最近写的一个个人项目(传送门:全终端云书签)中需要用到全文检索功能,目前 mysql,es 都可以做全文检索,mysql 胜在配置方便很快就能搞定上线(参考这里),不考虑上手难度,es 在全文检 ...
- springboot集成es7(基于high level client)
环境: ES: 7.12.0 1.springboot工程引入es相关jar <dependency> <groupId>org.elasticsearch</group ...
- ElasticSearch的javaAPI之Client
翻译的原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/client.html#node-c ...
- Java Elasticsearch新手入门教程
概要: 1.使用Eclipse搭建Elasticsearch详情参考下面链接 2.Java Elasticsearch 配置 3.ElasticSearch Java Api(一) -添加数据创建索引 ...
- java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: service-one
一.异常信息 java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have a ...
- spring .cloud ------------java.lang.RuntimeException: com.netflix.client.ClientException,Caused by: java.lang.IllegalArgumentException: MIME type may not contain reserved characters
1.问题的发生 Feign在默认情况下使用的是JDK原生的URLConnection发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,即利用HTTP的persistence connect ...
- java.lang.NoClassDefFoundError: org.androidpn.client.PersistentConnectionListener
在运行AndroidpnClient项目时出现了java.lang.NoClassDefFoundError: org.androidpn.client.PersistentConnectionLis ...
- [解决]java.lang.IllegalArgumentException: Bad level "DEBUG"
Tomcat启动报错,搞得烦的一比.常规思维就会迷瞪,谁让tomcat的日志级别特殊ne.... http://tomcat.apache.org/tomcat-7.0-doc/ 错误现象: Hand ...
- 上机题目(0基础)- Java网络操作-Socket实现client和server端通信二(Java)
上一节实现了client像server端发送请求.本节将实现server端向client回传信息.实现原理非常easy,在原来的基础上.在server端实现输出流,在client实现输入流就可以,详细 ...
- 上机题目(0基础)- Java网络操作-Socket实现client和server端通信(Java)
非常多刚開始学习的人对于java网络通信不太熟悉.对相关概念也不太明确,这里我们主要实现一下socket通信,socket通信在java中应用十分广泛.比如QQ和MSN等都是基于socket通信的,什 ...
随机推荐
- ADBPG&Greenplum成本优化之磁盘水位管理
简介:本文我们将通过一个实际的磁盘空间优化案例来说明,如何帮助客户做成本优化. 作者 | 玉翮 来源 | 阿里技术公众号 一 背景描述 目前,企业的核心数据一般都以二维表的方式存储在数据库中.在 ...
- StarLake:汇量科技云原生数据湖的探索和实践
简介: 快速了解汇量科技在云原生数据湖领域的探索和实践,详解 StarLake 的架构及业务应用案例. 作者:陈绪(汇量科技资深算法架构师,EnginePlus 2.0 产品负责人) 内容框架: 互联 ...
- [Py] Python 接口数据用 pandas 高效写入 csv
通过 pandas 把 dict 数据封装,调用接口方法写入 csv 文件. import pandas as pd data = [{"name": "a"} ...
- [Gin] gin.H{} 与 map[string]interface{}
gin.H 中的 H 是对 map[string]interface{} 定义的新类型,用来简化生成 map 数据时的书写. // H is a shortcut for map[string]int ...
- dotnet 6 通过 DOTNET_ROOT 让调起的应用的进程拿到共享的运行时文件夹
我的应用是独立发布的,在用户的设备上不需要额外去安装 .NET 运行时.但是我的应用有一个需求是下载另一个应用作为插件,由本应用调起插件进程.本文告诉大家如何解决调用插件的进程时,赋值给插件进程运行时 ...
- K8s集群中部署SpringCloud在线购物平台(三)
五.SpringCloud概述 springcloud架构图 5.1 SpringCloud是什么? 官网: https://spring.io/projects/spring-cloud Sprin ...
- golang复用http.request.body
golang复用http.request.body 问题及场景 业务当中有需要分发http.request.body的场景.比如微信回调消息只能指定一个地址,所以期望可以复制一份消息发给其他服务.由服 ...
- three.js教程8-渲染器WebGLRenderer和前端UI界面
1.html的UI交互界面与Canvas画布叠加 需求:把threejs Cavnas画布和HTML元素叠加布局,在canvas上添加按钮,通过按钮点击修改canvas场景. // canvas画布绝 ...
- 资源编排ROS之模块:实现模板代码复用(基础篇)
背景 资源编排服务(Resource Orchestration Service, 简称ROS)是阿里云提供的一项简化云计算资源管理的服务.您可以遵循ROS定义的模板规范编写资源栈模板,在模板中定义所 ...
- python利用flux基本读写influxDB
1.读取 QuerApi 形式 python 利用 flux 语句查询 influxdb 数据. https://influxdb-client.readthedocs.io/en/latest/ap ...