ElasticSearch数据检索实战
基础查询
查询聊天记录
查询:
- 指定发送者(
from.keyword
):TongXiaoEr - 聊天类型(
chatType
): 单聊 - 消息类型(
msgType
): 文本 - 关键次匹配(
text.content
):好的
排序:
- 消息时间(
msgTime
):倒序
bash
POST /gupaoedu-wxcp-msg-2024-06-*/_search
{
"size": 1,
"query": {
"bool": {
"must": [
{
"match": {
"from.keyword": "TongXiaoEr"
}
},
{
"term": {
"chatType": "1"
}
},
{
"term": {
"msgType": "text"
}
},
{
"match_phrase": {
"text.content": "好的"
}
}
]
}
},
"sort": [
{
"msgTime": {
"order": "desc"
}
}
]
}
java
Query q = Query.of(b -> b.bool(b1 -> b1.must(
Query.of(b2 -> b2.match(m -> m.field("from.keyword").query(t -> t.stringValue("TongXiaoEr")))),
Query.of(b2 -> b2.term(t -> t.field("chatType").value(FieldValue.of("1")))),
Query.of(b2 -> b2.term(t -> t.field("msgType").value(FieldValue.of("text")))),
Query.of(b2 -> b2.matchPhrase(m -> m.field("text.content").query("好的")))
)
));
// 构建搜索请求
SearchRequest searchRequest = SearchRequest.of(s -> s
.index("gupaoedu-wxcp-msg-2024-06-*")
.size(1)
.query(q)
.sort(SortOptions.of(so -> so
.field(f -> f
.field("msgTime")
.order(SortOrder.Desc)
)
))
);
SearchResponse<Map> searchResponse = client.search(searchRequest, Map.class);
// 序列化SearchResponse对象为JSON字符串
String jsonResponse = serializeResponseToJson(searchResponse);
System.out.println(jsonResponse);
json
{
"took" : 80,
"timed_out" : false,
"_shards" : {
"total" : 19,
"successful" : 19,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 83,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "gupaoedu-wxcp-msg-2024-06-19",
"_type" : "_doc",
"_id" : "1012599982130127612_1718777967324_external",
"_score" : null,
"_source" : {
"cropId" : "wwe2d76b4a3b7df43e",
"msgType" : "text",
"msgId" : "1012599982130127612_1718777967324_external",
"roomId" : "",
"@timestamp" : "2024-06-19T14:19:23.144+08:00",
"tolist" : [
"wmuppIEAAAV9D4H5gODlL1qiV5gZwPTQ"
],
"action" : "send",
"msgTime" : 1718777963144,
"from" : "TongXiaoEr",
"text" : {
"content" : "好的哦"
},
"chatType" : "1"
},
"sort" : [
1718777963144
]
}
]
}
}