Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
Kwan的解忧杂货铺@新空间代码工作室
elasticsearch-demo
提交
dc74f121
E
elasticsearch-demo
项目概览
Kwan的解忧杂货铺@新空间代码工作室
/
elasticsearch-demo
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
E
elasticsearch-demo
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
提交
dc74f121
编写于
5月 10, 2023
作者:
Kwan的解忧杂货铺@新空间代码工作室
🐭
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
fix:测试
上级
f8ae6d99
变更
7
隐藏空白更改
内联
并排
Showing
7 changed file
with
439 addition
and
0 deletion
+439
-0
pom.xml
pom.xml
+37
-0
src/main/java/com/kwan/shuyu/SearchApplication.java
src/main/java/com/kwan/shuyu/SearchApplication.java
+12
-0
src/main/java/com/kwan/shuyu/config/ElasticsearchConfig.java
src/main/java/com/kwan/shuyu/config/ElasticsearchConfig.java
+33
-0
src/main/resources/application.yml
src/main/resources/application.yml
+6
-0
src/main/resources/logback-spring.xml
src/main/resources/logback-spring.xml
+47
-0
src/test/java/TestDemo.java
src/test/java/TestDemo.java
+32
-0
src/test/java/TestDocument.java
src/test/java/TestDocument.java
+272
-0
未找到文件。
pom.xml
浏览文件 @
dc74f121
...
...
@@ -13,4 +13,41 @@
<maven.compiler.target>
8
</maven.compiler.target>
</properties>
<dependencies>
<!--es客户端-->
<dependency>
<groupId>
org.elasticsearch.client
</groupId>
<artifactId>
elasticsearch-rest-high-level-client
</artifactId>
<version>
7.3.0
</version>
<exclusions>
<exclusion>
<groupId>
org.elasticsearch
</groupId>
<artifactId>
elasticsearch
</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>
org.elasticsearch
</groupId>
<artifactId>
elasticsearch
</artifactId>
<version>
7.3.0
</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter
</artifactId>
<version>
2.0.6.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-test
</artifactId>
<scope>
test
</scope>
<version>
2.0.6.RELEASE
</version>
</dependency>
<dependency>
<groupId>
org.projectlombok
</groupId>
<artifactId>
lombok
</artifactId>
<version>
1.16.10
</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
src/main/java/com/kwan/shuyu/SearchApplication.java
0 → 100644
浏览文件 @
dc74f121
package
com.kwan.shuyu
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
@SpringBootApplication
public
class
SearchApplication
{
public
static
void
main
(
String
[]
args
)
{
SpringApplication
.
run
(
SearchApplication
.
class
,
args
);
}
}
src/main/java/com/kwan/shuyu/config/ElasticsearchConfig.java
0 → 100644
浏览文件 @
dc74f121
package
com.kwan.shuyu.config
;
import
org.apache.http.HttpHost
;
import
org.elasticsearch.client.RestClient
;
import
org.elasticsearch.client.RestHighLevelClient
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
/**
* es的配置类
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/5/10 12:37
*/
@Configuration
public
class
ElasticsearchConfig
{
@Value
(
"${kwan.elasticsearch.hostlist}"
)
private
String
hostlist
;
@Bean
(
destroyMethod
=
"close"
)
public
RestHighLevelClient
restHighLevelClient
()
{
String
[]
split
=
hostlist
.
split
(
","
);
HttpHost
[]
httpHostsArray
=
new
HttpHost
[
split
.
length
];
for
(
int
i
=
0
;
i
<
split
.
length
;
i
++)
{
String
item
=
split
[
i
];
httpHostsArray
[
i
]
=
new
HttpHost
(
item
.
split
(
":"
)[
0
],
Integer
.
parseInt
(
item
.
split
(
":"
)[
1
]),
"http"
);
}
return
new
RestHighLevelClient
(
RestClient
.
builder
(
httpHostsArray
));
}
}
\ No newline at end of file
src/main/resources/application.yml
0 → 100644
浏览文件 @
dc74f121
spring
:
application
:
name
:
search-service
kwan
:
elasticsearch
:
hostlist
:
47.119.160.231:9200
#多个节点用逗号分隔
\ No newline at end of file
src/main/resources/logback-spring.xml
0 → 100644
浏览文件 @
dc74f121
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--定义日志文件的存储地址,使用绝对路径-->
<property
name=
"LOG_HOME"
value=
"d:/logs"
/>
<!-- Console 输出设置 -->
<appender
name=
"CONSOLE"
class=
"ch.qos.logback.core.ConsoleAppender"
>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
<charset>
utf8
</charset>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender
name=
"FILE"
class=
"ch.qos.logback.core.rolling.RollingFileAppender"
>
<rollingPolicy
class=
"ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
>
<!--日志文件输出的文件名-->
<fileNamePattern>
${LOG_HOME}/xc.%d{yyyy-MM-dd}.log
</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<!-- 异步输出 -->
<appender
name=
"ASYNC"
class=
"ch.qos.logback.classic.AsyncAppender"
>
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>
0
</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>
512
</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref
ref=
"FILE"
/>
</appender>
<logger
name=
"org.apache.ibatis.cache.decorators.LoggingCache"
level=
"INFO"
additivity=
"false"
>
<appender-ref
ref=
"CONSOLE"
/>
</logger>
<logger
name=
"org.springframework.boot"
level=
"INFO"
/>
<root
level=
"info"
>
<!--<appender-ref ref="ASYNC"/>-->
<appender-ref
ref=
"FILE"
/>
<appender-ref
ref=
"CONSOLE"
/>
</root>
</configuration>
\ No newline at end of file
src/test/java/TestDemo.java
0 → 100644
浏览文件 @
dc74f121
import
org.apache.http.HttpHost
;
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
java.io.IOException
;
/**
* 普通项目查询es,获取数据
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/5/10 11:50
*/
public
class
TestDemo
{
public
static
void
main
(
String
[]
args
)
throws
IOException
{
//1获取连接客户端
RestHighLevelClient
client
=
new
RestHighLevelClient
(
RestClient
.
builder
(
new
HttpHost
(
"47.119.160.231"
,
9200
,
"http"
)
));
//2构建请求
GetRequest
getRequest
=
new
GetRequest
(
"book"
,
"1"
);
//3执行
GetResponse
getResponse
=
client
.
get
(
getRequest
,
RequestOptions
.
DEFAULT
);
//4获取结果
System
.
out
.
println
(
getResponse
.
getId
());
System
.
out
.
println
(
getResponse
.
getVersion
());
System
.
out
.
println
(
getResponse
.
getSourceAsString
());
}
}
\ No newline at end of file
src/test/java/TestDocument.java
0 → 100644
浏览文件 @
dc74f121
import
com.kwan.shuyu.SearchApplication
;
import
lombok.extern.slf4j.Slf4j
;
import
org.elasticsearch.action.DocWriteResponse
;
import
org.elasticsearch.action.bulk.BulkItemResponse
;
import
org.elasticsearch.action.bulk.BulkRequest
;
import
org.elasticsearch.action.bulk.BulkResponse
;
import
org.elasticsearch.action.delete.DeleteRequest
;
import
org.elasticsearch.action.delete.DeleteResponse
;
import
org.elasticsearch.action.get.GetRequest
;
import
org.elasticsearch.action.get.GetResponse
;
import
org.elasticsearch.action.index.IndexRequest
;
import
org.elasticsearch.action.index.IndexResponse
;
import
org.elasticsearch.action.support.replication.ReplicationResponse
;
import
org.elasticsearch.action.update.UpdateRequest
;
import
org.elasticsearch.action.update.UpdateResponse
;
import
org.elasticsearch.client.RequestOptions
;
import
org.elasticsearch.client.RestHighLevelClient
;
import
org.elasticsearch.common.xcontent.XContentType
;
import
org.junit.Test
;
import
org.junit.runner.RunWith
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.boot.test.context.SpringBootTest
;
import
org.springframework.test.context.junit4.SpringRunner
;
import
java.io.IOException
;
import
java.util.HashMap
;
import
java.util.Map
;
@Slf4j
@SpringBootTest
(
classes
=
SearchApplication
.
class
)
@RunWith
(
SpringRunner
.
class
)
public
class
TestDocument
{
@Autowired
RestHighLevelClient
client
;
@Test
public
void
testGet
()
throws
IOException
{
// 1构建请求
GetRequest
getRequest
=
new
GetRequest
(
"test_post"
,
"1"
);
// ===========可选参数==========
// String[] includes=new String[]{"user","message"};
// String[] excludes= Strings.EMPTY_ARRAY;
// FetchSourceContext fetchSourceContext=new FetchSourceContext(true, includes, excludes);
// getRequest.fetchSourceContext(fetchSourceContext);
// String[] includes=Strings.EMPTY_ARRAY;
// String[] excludes= new String[]{"user","message"};
// FetchSourceContext fetchSourceContext=new FetchSourceContext(true, includes, excludes);
// getRequest.fetchSourceContext(fetchSourceContext);
// getRequest.routing("routing");
// 2执行
// 同步查询
GetResponse
getResponse
=
client
.
get
(
getRequest
,
RequestOptions
.
DEFAULT
);
//异步查询
// ActionListener<GetResponse> listener=new ActionListener<GetResponse>() {
// //成功时
// public void onResponse(GetResponse getResponse) {
// System.out.println(getResponse.getId());
//// System.out.println(getResponse.getVersion());
//// System.out.println(getResponse.getSourceAsString());
// }
// //失败时
// public void onFailure(Exception e) {
// e.printStackTrace();
// }
// };
//
// client.getAsync(getRequest, RequestOptions.DEFAULT, listener);
//
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// 3获取结果
if
(
getResponse
.
isExists
())
{
System
.
out
.
println
(
getResponse
.
getId
());
System
.
out
.
println
(
getResponse
.
getVersion
());
System
.
out
.
println
(
getResponse
.
getSourceAsString
());
//以string获取数据
System
.
out
.
println
(
getResponse
.
getSourceAsBytes
());
////以Bytes获取数据
System
.
out
.
println
(
getResponse
.
getSourceAsMap
());
//以Map获取数据
}
else
{
log
.
info
(
"数据不存在"
);
}
}
@Test
public
void
testAdd
()
throws
IOException
{
// PUT test_post/_doc/2
// {
// "user":"tomas",
// "postDate":"2019-07-18",
// "message":"trying out es1"
// }
// 1构建请求
IndexRequest
request
=
new
IndexRequest
(
"test_post"
);
request
.
id
(
"5"
);
// ======================构建文档数据=======================
//方法1
String
jsonString
=
"{\n"
+
" \"user\":\"tomas\",\n"
+
" \"postDate\":\"2019-07-18\",\n"
+
" \"message\":\"trying out es1\"\n"
+
"}"
;
request
.
source
(
jsonString
,
XContentType
.
JSON
);
//方法2
// Map<String, Object> jsonMap = new HashMap<String, Object>();
// jsonMap.put("user", "tomas");
// jsonMap.put("postDate", "2019-07-18");
// jsonMap.put("message", "trying out es1");
// request.source(jsonMap);
//方法3
// XContentBuilder builder = XContentFactory.jsonBuilder();
// builder.startObject();
// {
// builder.field("user", "tomas");
// builder.field("message", "trying out es1");
// builder.timeField("postDate", "2019-07-18");
// }
// builder.endObject();
// request.source(builder);
//方法4
// request.source("user", "tomas",
// "message", "trying out es1",
// "postDate", "2019-07-18");
// =====可选参数==
//设置超时时间
// request.timeout("1s");
// request.timeout(TimeValue.timeValueSeconds(1));
//手动维护版本号
// request.version(4);
// request.versionType(VersionType.EXTERNAL);
// 2执行
//同步
IndexResponse
indexResponse
=
client
.
index
(
request
,
RequestOptions
.
DEFAULT
);
// 异步
// ActionListener<IndexResponse> listener=new ActionListener<IndexResponse>() {
// //成功时
// public void onResponse(IndexResponse indexResponse) {
// System.out.println(indexResponse.getIndex());
// System.out.println(indexResponse.getId());
// System.out.println(indexResponse.getResult());
// }
// //失败时
// public void onFailure(Exception e) {
//
// }
// };
//
// client.indexAsync(request, RequestOptions.DEFAULT, listener);
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// 3获取结果
System
.
out
.
println
(
indexResponse
.
getIndex
());
System
.
out
.
println
(
indexResponse
.
getId
());
System
.
out
.
println
(
indexResponse
.
getResult
());
if
(
indexResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
CREATED
)
{
DocWriteResponse
.
Result
result
=
indexResponse
.
getResult
();
System
.
out
.
println
(
"CREATE"
+
result
);
}
else
if
(
indexResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
UPDATED
)
{
DocWriteResponse
.
Result
result
=
indexResponse
.
getResult
();
System
.
out
.
println
(
"UPDATED"
+
result
);
}
else
{
}
// "_shards" : {
// "total" : 2,
// "successful" : 1,
// "failed" : 0
// }
ReplicationResponse
.
ShardInfo
shardInfo
=
indexResponse
.
getShardInfo
();
if
(
shardInfo
.
getTotal
()
!=
shardInfo
.
getSuccessful
())
{
System
.
out
.
println
(
"处理成功的分片数少于总分片!"
);
}
if
(
shardInfo
.
getFailed
()
>
0
)
{
for
(
ReplicationResponse
.
ShardInfo
.
Failure
failure
:
shardInfo
.
getFailures
())
{
String
reason
=
failure
.
reason
();
//每一个错误的原因
System
.
out
.
println
(
reason
);
}
}
}
@Test
public
void
testUpdate
()
throws
IOException
{
// POST test_post/_doc/3/_update
// {
// "doc":{
// "user":"tomas Lee"
// }
// }
// 1创建请求
UpdateRequest
request
=
new
UpdateRequest
(
"test_post"
,
"3"
);
Map
<
String
,
Object
>
jsonMap
=
new
HashMap
<>();
jsonMap
.
put
(
"user"
,
"tomas Lee"
);
request
.
doc
(
jsonMap
);
// =========可选参数========
request
.
timeout
(
"1s"
);
request
.
retryOnConflict
(
3
);
//重试次数
// 2执行
//同步
UpdateResponse
updateResponse
=
client
.
update
(
request
,
RequestOptions
.
DEFAULT
);
//异步
// 3获取结果
updateResponse
.
getId
();
updateResponse
.
getIndex
();
//判断结果
if
(
updateResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
CREATED
)
{
DocWriteResponse
.
Result
result
=
updateResponse
.
getResult
();
System
.
out
.
println
(
"CREATED:"
+
result
);
}
else
if
(
updateResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
UPDATED
)
{
DocWriteResponse
.
Result
result
=
updateResponse
.
getResult
();
System
.
out
.
println
(
"UPDATED:"
+
result
);
}
else
if
(
updateResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
DELETED
)
{
DocWriteResponse
.
Result
result
=
updateResponse
.
getResult
();
System
.
out
.
println
(
"DELETED:"
+
result
);
}
else
if
(
updateResponse
.
getResult
()
==
DocWriteResponse
.
Result
.
NOOP
)
{
//没有操作
DocWriteResponse
.
Result
result
=
updateResponse
.
getResult
();
System
.
out
.
println
(
"NOOP:"
+
result
);
}
}
@Test
public
void
testDelete
()
throws
IOException
{
// 1创建请求
DeleteRequest
request
=
new
DeleteRequest
(
"test_post"
,
"3"
);
//可选参数
// 2执行
DeleteResponse
deleteResponse
=
client
.
delete
(
request
,
RequestOptions
.
DEFAULT
);
// 3获取结果
deleteResponse
.
getId
();
deleteResponse
.
getIndex
();
DocWriteResponse
.
Result
result
=
deleteResponse
.
getResult
();
System
.
out
.
println
(
result
);
}
@Test
public
void
testBulk
()
throws
IOException
{
// 1创建请求
BulkRequest
request
=
new
BulkRequest
();
// request.add(new IndexRequest("post").id("1").source(XContentType.JSON,"field","1" ));
// request.add(new IndexRequest("post").id("2").source(XContentType.JSON,"field","2" ));
request
.
add
(
new
UpdateRequest
(
"post"
,
"1"
).
doc
(
XContentType
.
JSON
,
"field"
,
"3"
));
request
.
add
(
new
DeleteRequest
(
"post"
).
id
(
"2"
));
// 2执行
BulkResponse
bulkResponse
=
client
.
bulk
(
request
,
RequestOptions
.
DEFAULT
);
// 3获取结果
for
(
BulkItemResponse
itemResponse
:
bulkResponse
)
{
DocWriteResponse
response
=
itemResponse
.
getResponse
();
switch
(
itemResponse
.
getOpType
())
{
case
INDEX:
IndexResponse
indexResponse
=
(
IndexResponse
)
response
;
System
.
out
.
println
(
"INDEX:"
+
indexResponse
.
getResult
());
break
;
case
CREATE:
IndexResponse
createResponse
=
(
IndexResponse
)
response
;
System
.
out
.
println
(
"CREATE:"
+
createResponse
.
getResult
());
break
;
case
UPDATE:
UpdateResponse
updateResponse
=
(
UpdateResponse
)
response
;
System
.
out
.
println
(
"UPDATE:"
+
updateResponse
.
getResult
());
break
;
case
DELETE:
DeleteResponse
deleteResponse
=
(
DeleteResponse
)
response
;
System
.
out
.
println
(
"DELETE:"
+
deleteResponse
.
getResult
());
break
;
}
}
}
}
\ No newline at end of file
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录