1. 程式人生 > 實用技巧 >ElasticSearch搜尋

ElasticSearch搜尋

1、準備資料

1) 建立索引

2) 建立mapping

JSON資料如下

{
"properties": {
"id": {
"type": "long"
},
"age": {
"type": "integer"
},
"username": {
"type": "keyword"
},
"nickname": {
"type": "text",
"analyzer": "ik_max_word"
},
"money": {
"type": "float"
},
"desc": {
"type": "text",
"analyzer": "ik_max_word"
},
"sex": {
"type": "byte"
},
"birthday": {
"type": "date"
},
"face": {
"type": "text",
"index": false
}
}
}

  

3) 增加多條資料

http://192.168.127.130:9200/user/_doc/1001

JSON如下":

{
	"id": 1001,
	"age": 20,
	"username": "張三",
	"nickname": "小張",
	"money": 18.6,
	"desc": "我在中華學習網學習",
	"sex": 0,
	"birthday": "1920-07-14",
	"face": "https://www.baidu.com/imgs/08/heh.png"
}


然後修改id,增加多條資料

2、QueryString方式搜尋

將搜尋的欄位和值拼接到Url中

根據索引中某個欄位搜尋

根據desc搜尋

GET請求 http://192.168.127.130:9200/user/_search?q=desc:中華

多條件搜尋: 根據desc和age進行搜尋

http://192.168.127.130:9200/user/_search?q=desc:中華&q=age:20

QueryString用的很少,複雜測查詢引數難以構建,所以大多查詢都會使用dsl進行查詢更好。

3、DSL方式搜尋

DSL: Domain Specific Language 特定領域語言,基於JSON格式的查詢,查詢更靈活,有利於複雜查詢

1) 查詢desc單個欄位

http://192.168.127.130:9200/user/_doc/_search

2) 查詢某個欄位是否存在

4、查詢所有和分頁

1) 查詢所有

GET http://192.168.127.130:9200/user/_doc/_search

DSL方式查詢所有, match_all

2) 查詢指定要查詢欄位的所有資料

如下圖,只查詢id,nickname,age

3) 分頁查詢

from 從第0條開始

size: 每頁顯示10條

4) head 視覺化查詢

5) term精確搜尋

,把搜尋的內容,如“中華學習網”作為一個整個關鍵詞去搜索,不會做分詞搜尋

desc包括有“中華學習網”,就能查詢到。 將term換成match後,“中華學習網”會進行分詞,將所有匹配分詞的結果都能查詢出來。

{
	"query": {
		"term": {
			"desc": "中華學習網"
		}
	},
	"_source": [
		"id",
		"nickname",
		"age"
	]
	
}

  

terms 多個詞語匹配檢索

相當於tag標籤查詢,比如部落格的文章打上了tag, “前端”,“後端”,“ElasticSerach”,完全可以用標籤匹配查詢