一、索引
ES里,數(shù)據(jù)庫(kù)(Database)對(duì)應(yīng)的概念叫 索引(Index)。
1. 創(chuàng)建索引
PUT http://127.0.0.1:9200/shopping
2. 查看所有索引
GET http://127.0.0.1:9200/_cat/indices?v
3. 刪除索引
DELETE http://127.0.0.1:9200/shopping
二、文檔
ES里,數(shù)據(jù)庫(kù)的表(Table)對(duì)應(yīng)的概念是 類(lèi)型(Type)。
然而在新版本ES里,已經(jīng)棄用類(lèi)型(Type)的概念了。
ES里,數(shù)據(jù)庫(kù)的行(row)對(duì)應(yīng)的概念是 文檔(Document)。
1. 創(chuàng)建文檔
POST http://127.0.0.1:9200/shopping/_doc 或
POST http://127.0.0.1:9200/shopping/_create
{
"title":"小米手機(jī)",
"category":"小米",
"images":"http://www.gulixueyuan.com/xm.jpg",
"price":3999.00
}
手動(dòng)指定ID:URL后加上 /{id}
2. 查詢(xún)單條文檔
GET http://127.0.0.1:9200/shopping/_doc/1001
3. 查詢(xún)所有文檔
GET http://127.0.0.1:9200/shopping/_search
4. 修改文檔
分為完全修改和部分修改。
完全修改
PUT http://127.0.0.1:9200/shopping/_doc/1001
{
"title":"小米手機(jī)",
"category":"小米",
"images":"http://www.gulixueyuan.com/xm.jpg",
"price":4999.00
}
部分修改
POST http://127.0.0.1:9200/shopping/_update/1001
{
"doc": {
"title": "華為手機(jī)"
}
}
5. 刪除文檔
DELETE http://127.0.0.1:9200/shopping/_doc/1001
三、查詢(xún)
方式1:
GET http://127.0.0.1:9200/shopping/_search?q=category:小米
方式2(推薦):
GET http://127.0.0.1:9200/shopping/_search
{
"query": {
"match": {
"category": "小米"
}
}
}
match 改為 match_all 即為全量查詢(xún)。
分頁(yè)查詢(xún)
{
"query": {
"match": {
"category": "小米"
}
},
"from": 0,
"size": 2
}
限制查詢(xún)字段
{
"query": {
"match": {
"category": "小米"
}
},
"from": 0,
"size": 2,
"_source": ["title"]
}
排序
{
"query": {
"match": {
"category": "小米"
}
},
"from": 0,
"size": 2,
"_source": ["title"],
"sort": {
"price": {
"order": "desc"
}
}
}
多條件查詢(xún) bool,AND:關(guān)鍵字 must
{
"query": {
"bool": {
"must": [
{
"match": {
"category": "小米"
}
},
{
"match": {
"price": 3999.00
}
}
]
}
}
}
多條件查詢(xún),OR:關(guān)鍵字 should
{
"query": {
"bool": {
"should": [
{
"match": {
"category": "小米"
}
},
{
"match": {
"price": 3999.00
}
}
]
}
}
}
結(jié)果按范圍過(guò)濾,關(guān)鍵字 filter
{
"query": {
"bool": {
"should": [
{
"match": {
"category": "小米"
}
},
{
"match": {
"price": 3999.00
}
}
],
"filter": {
"range": {
"price": {
"gt": 3500
}
}
}
}
}
}
完全匹配 match_phrase
上面的 match 和 match_all 都屬于模糊查詢(xún),會(huì)拆分關(guān)鍵詞
如果要作為整體進(jìn)行查詢(xún),應(yīng)該用 match_phrase
{
"query": {
"match_phrase": {
"category": "小華"
}
}
}
高亮查詢(xún)
{
"query": {
"match": {
"category": "小華"
}
},
"highlight": {
"fields": {
"category": {}
}
}
}
聚合查詢(xún) aggs
{
"aggs": { //聚合操作
"price_group": { //名稱(chēng),隨意起名
"terms": { //分組
"field": "price" //分組字段
}
}
}
}
聚合查詢(xún),只留統(tǒng)計(jì)結(jié)果
{
"aggs": {
"price_group": {
"terms": {
"field": "price"
}
}
},
"size": 0
}