文章來自
Elasticsearch操作索引
前提
- 下載好Kibana,在Kibana打開后的頁面里輸入下面的內容進行測試,實際上Kibana的測試功能就是一個postman,但是比postman強大得多的是,可視化的數據分析,圖標分析等等
ES的數據結構
索引(indices)------Databases 表
文檔(Document)--------Row 行
字段(Field)----Columns 列
基礎使用
// 新增數據
POST /heima/goods/
{
"title":"小米手機",
"images":"http://image.leyou.com/12479122.jpg",
"price":2699.00
}
// 查看數據
GET /heima/_search
{
"query":{
"match_all": {}
}
}
// 查看數據的返回結果,id是隨機生成的
{
"_index": "heima",
"_type": "goods",
"_id": "r9c1KGMBIhaxtY5rlRKv",
"_version": 1,
"_score": 1,
"_source": {
"title": "小米手機",
"images": "http://image.leyou.com/12479122.jpg",
"price": 2699
}
}
// 查看數據庫結構
GET /heima/_mapping
{
"heima": {
"mappings": {
"goods": {
"properties": {
"images": {
"type": "keyword",
"index": false
},
"price": {
"type": "float"
},
"title": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
}
}
// 自定義id存入
POST /heima/goods/2
{
"title":"大米手機",
"images":"http://image.leyou.com/12479122.jpg",
"price":2899.00
}
// 以id的方式再次存入就是修改,隨機id需要先獲取id
POST /heima/goods/2
{
"title":"小米手機",
"images":"http://image.leyou.com/12479122.jpg",
"price":1899.00
}
// 刪除數據
DELETE /索引庫名/類型名/id值
// 模糊搜索,會使用分詞
GET /heima/_search
{
"query":{
"match":{
"title":"小米電視"
}
}
}
// 模糊搜索,不使用
GET /heima/_search
{
"query":{
"match": {
"title": {
"query": "小米電視",
"operator": "and"
}
}
}
}
// 組合查詢
GET /heima/_search
{
"query":{
"multi_match": {
"query": "小米",
"fields": [ "title", "subTitle" ]
}
}
}
// 多詞條精確匹配
GET /heima/_search
{
"query":{
"terms":{
"price":[2699.00,2899.00,3899.00]
}
}
}
// 只要指定的字段就行
GET /heima/_search
{
"_source": {
"includes":["title","price"]
},
"query": {
"term": {
"price": 2699
}
}
}
// 排除這個字段
GET /heima/_search
{
"_source": {
"excludes": ["images"]
},
"query": {
"term": {
"price": 2699
}
}
}
高級查詢
// 過濾
GET /heima/_search
{
"query":{
"constant_score": {
"filter": {
"range":{"price":{"gt":2000.00,"lt":3000.00}}
}
}
}
// 排序
GET /heima/_search
{
"query": {
"match": {
"title": "小米手機"
}
},
"sort": [
{
"price": {
"order": "desc"
}
}
]
}
// 多字段排序
GET /goods/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手機" }},
"filter":{
"range":{"price":{"gt":200000,"lt":300000}}
}
}
},
"sort": [
{ "price": { "order": "desc" }},
{ "_score": { "order": "desc" }}
]
}
聚合aggregations,就是sql的分組
// 用color字段作為分組
// size: 查詢條數,這里設置為0,因為我們不關心搜索到的數據,只關心聚合結果,提高效率
// aggs:聲明這是一個聚合查詢,是aggregations的縮寫
// popular_colors:給這次聚合起一個名字,任意。
// terms:划分桶的方式,這里是根據詞條划分
// field:划分桶的字段
GET /cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color"
}
}
}
}
// 用顏色做分組后還要計算價格
GET /cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color"
},
"aggs":{
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
更多高端操作查看最上面的原文