Elasticsearch 論壇實戰-使用term filter來搜尋資料
阿新 • • 發佈:2020-12-18
技術標籤:Elasticsearch實戰elasticsearch
Elasticsearch實戰
根據使用者ID、是否隱藏、帖子ID、發帖日期來搜尋帖子
PUT /forum/post/_bulk {"index":{"_id":1}} {"id":"XHDK-A-1293-#fJ3","userId":1,"postDate":"2020-12-16","hidden":true} {"index":{"_id":2}} {"id":"XGFJ-A-1273-#fJ3","userId":2,"postDate":"2020-12-15","hidden":false} {"index":{"_id":3}} {"id":"AHFS-A-2393-#ad5","userId":3,"postDate":"2020-11-05","hidden":false} {"index":{"_id":4}} {"id":"AJFS-A-2393-#as3","userId":3,"postDate":"2020-10-13","hidden":true}
檢視下mapping,es7版本,type=text,預設會設定兩個field,一個是field本身,比如articleID,就是分詞的;還有一個的話,就是field.keyword預設不分詞,會最多保留256個字元
GET /forum/_mapping/post?include_type_name=true
#! Deprecation: [types removal] Using include_type_name in get mapping requests is deprecated. The parameter will be removed in the next major version.
{
"forum" : {
"mappings" : {
"post" : {
"properties" : {
"hidden" : {
"type" : "boolean"
},
"id" : {
"type" : "text",
"fields" : {
"keyword" : {"type" : "keyword",
"ignore_above" : 256
}
}
},
"postDate" : {
"type" : "date"
},
"userId" : {
"type" : "long"
}
}
}
}
}
}
根據使用者ID搜尋帖子
# 這樣查詢沒有資料,因為term是完全匹配
GET /forum/post/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"id": "XHDK-A-1293-#fJ3"
}
}
]
}
}
}
# 這樣可以查詢資料,因為field.keyword預設不分詞,會最多保留256個字元
GET /forum/post/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"id.keyword": "XHDK-A-1293-#fJ3"
}
}
]
}
}
}
設定id型別為keyword後再用第一條查詢就會出來資料了
PUT /forum?include_type_name=true
{
"mappings": {
"post":{
"properties":{
"id":{
"type":"keyword"
}
}
}
}
}
搜尋沒有隱藏的帖子
GET /forum/post/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"hidden": false
}
}
]
}
}
}
根據發帖日期搜尋帖子
GET /forum/post/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"postDate": "2020-12-15"
}
}
]
}
}
}