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通信的,什 ...
随机推荐
- [FAQ] edge debug栏的网络里 没有见到 All Fetch/XHR JS CSS 这些东西
一种方式是 打开调试器的设置,重置默认并刷新即可. 另一种方式是把这个 "筛选" 点掉. Tool:揭开网站所用的技术 Link:https://www.cnblogs.com ...
- [FAQ] Vue iframe 的 src 是链接地址却加载了相对路径 ?
iframe 的 src 是链接, 但是加载的实际链接是相对路径,只有一种可能:链接地址不正确. 检查链接有没有少符号,常见错误:http//,http:/ Refer:Vue的iframe错误 Li ...
- dotnet 6 修复找不到 EnumeratorToEnumVariantMarshaler 问题
我将在一个 .NET Framework 项目升级到 dotnet 6 时发现构建不通过,因为原先的代码使用到了 EnumeratorToEnumVariantMarshaler 类型,在 dotne ...
- WPF 框架开发 ColumnDefinition 和 RowDefinition 的代码在哪
我的 VisualStudio 在更新到 2022 就构建不通过 WPF 仓库,提示我在 Grid 的代码里面找不到 ColumnDefinitionCollection 和 RowDefinitio ...
- Intel Pentium III CPU(Coppermine, Tualatin) L2 Cache Latency, Hardware Prefetch特性调查
这几天,偶然的机会想到了困扰自己和其他网友多年的Intel Pentium III系列处理器缓存延迟(L2 Cache Latency),以及图拉丁核心版本是否支持硬件预取(Hardware Pref ...
- CF1912K
题意:给定一个长度为 n 的序列,求有多少个子序列满足该子序列内任意相邻 3 个数的和为偶数. 只与奇偶有关,所以可以把状态转化为 01 的. 设 \(f[i][x][y]\) 表示在前 i 个数中, ...
- 阿里巴巴MySQL开源中间件Canal入门
前言 距离上一篇文章发布又过去了两周,这次先填掉上一篇秒杀系统文章结尾处开的坑,介绍一下数据库中间件Canal的使用. Canal用途很广,并且上手非常简单,小伙伴们在平时完成公司的需求时,很有可能会 ...
- redis-desktop-manager-0.8.0.3844
redis-desktop-manager-0.8.0.3844 下载地址: https://www.aliyundrive.com/s/Y2fobkVjAdF 链接:https://pan.baid ...
- Vue3 项目
创建 Vue3 项目的步骤如下: 安装 Node.js Vue3 需要依赖 Node.js 环境,因此需要先安装 Node.js.可以从官网下载 Node.js 的安装包并安装,也可以使用包管理器安装 ...
- 几行命令用minikube快速搭建可测试的kubernetes单节点环境
几行命令用minikube快速搭建可测试的kubernetes单节点环境 需要docker环境,https://www.cnblogs.com/xiaofei12/p/17544579.html,网速 ...