ElasticSearch基础操作

发布时间 2024-01-12 16:01:53作者: 自学Java笔记本

ES基础操作

创建索引

通过PUT请求发起操作,对于put请求来说,是有幂等性的,只能发送一次请求,创建成功后再次创建就会报错了。

http://localhost:9200/shopping // 此时创建一个shopping索引的库
// 创建成功后返回如下格式:
{
	"acknowledged": true,
	"shards_acknowledged": true,
	"index": "shopping"
}

获取索引

通过GET请求获取

http://localhost:9200/shopping
// 获取成功后,格式如下:
{
	"shopping": {
		"aliases": {},
		"mappings": {},
		"settings": {
			"index": {
				"creation_date": "1704957496946",
				"number_of_shards": "1",
				"number_of_replicas": "1",
				"uuid": "juRaTvutQFKufB9DE11SkA",
				"version": {
					"created": "7080099"
				},
				"provided_name": "shopping"
			}
		}
	}
}

查看所有索引

通过GET请求,在请求参数中添加/_cat/indices?v

http://localhost:9200/_cat/indices?v
// 结果展示如下:
health status index            uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   app_info_article vr-rpKO-Tzq2-Ka9cZfKJw   1   1         29            1     43.5kb         43.5kb
yellow open   user             7SMtDKl-StWgcIoDXqUigw   1   1          4            0      4.5kb          4.5kb
yellow open   shopping         juRaTvutQFKufB9DE11SkA   1   1          0            0       208b           208b

删除索引

通过DELETE请求,在请求地址中加上索引名称

http://localhost:9200/shopping

//产出成功响应如下:
{
	"acknowledged": true
}

创建文档

索引中添加文档

索引已经创建好了,接下来我们来创建文档,并添加数据。这里的文档可以类比为关系型数
据库中的表数据,添加的数据格式为 JSON 格式
在 Postman 中,向 ES 服务器发 POST PUT请求 :http://localhost:9200/shopping/_doc/1001
需要在请求体中添加数据:

{
 "title":"小米手机",
 "category":"小米",
 "images":"http://www.gulixueyuan.com/xm.jpg",
 "price":3999.00
}
// 返回成功后的数据:
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1001",
	"_version": 2,
	"result": "updated",
	"_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 36,
	"_primary_term": 1
}

查询文档

通过GET请求查询文档

http://localhost:9200/shopping/_doc/1001
//返回的数据:
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1001",
	"_version": 2,
	"_seq_no": 36,
	"_primary_term": 1,
	"found": true,
	"_source": {
		"title": "小米手机",
		"category": "小米",
		"images": "http://www.gulixueyuan.com/xm.jpg",
		"price": 3999
	}
}

查询指定索引下的所有文档

http://localhost:9200/shopping/_search
通过/_search 查询

http://localhost:9200/shopping/_search
// 返回数据:
{
	"took": 150,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 36,
			"relation": "eq"
		},
		"max_score": 1,
		"hits": [
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "Owdy94wBoOAS7vbC9TP5",
				"_score": 1,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				}
			},
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "Rgd894wBoOAS7vbCWjPZ",
				"_score": 1,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				}
			}
		]
	}
}

修改文档

全量幂等性更新

http://localhost:9200/shopping/_doc/1001

添加请求体参数:
{
	"title": "小米手机",
	"category": "小米",
	"images": "http://www.gulixueyuan.com/xm.jpg",
	"price": 3999
}

//修改结果:
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1001",
	"_version": 4,
	"result": "updated", // 显示updated
	"_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 38,
	"_primary_term": 1
}

局部跟新文档

http://localhost:9200/shopping/_update/1001
通过关键url/_update/xxx

http://localhost:9200/shopping/_update/1001
//添加修改的参数,在请求体中添加
{
	"doc":{
        "title":"华为手机"
    }
}

// 返回结果:
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1001",
	"_version": 6,
	"result": "updated",
	"_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 40,
	"_primary_term": 1
}

删除文档

通过DELETE请求删除文档
http://localhost:9200/shopping/_doc/1001

http://localhost:9200/shopping/_doc/1001
// 返回结果
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1001",
	"_version": 7,
	"result": "deleted",
	"_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 41,
	"_primary_term": 1
}

复杂查询

复杂查询-请求路径参数查询

http://localhost:9200/shopping/_search?q=category:小米
通过url/_search?q=xxx:xxx 查询,该查询容易出错,当携带中文时容易乱码,一般采用post,请求体的方式

复杂查询-请求体参数查询

通过 POST请求 http://localhost:9200/shopping/_search
在请求体参数中添加:

{
    "query":{
        // match 表示匹配查询
		// match_all 表示全文查询
        "match":{
            "category":"小米"
        }
    }
}

复杂查询-分页查询

通过POST请求:http://localhost:9200/shopping/_search

// 请求体参数如下:
{
    "query":{
	   // match 表示匹配查询
        "match":{
            "category":"小米"
        }
    },
    "from":0, // 表示起始位置
    "size":2 //表示两条
}
// 返回结果如下:
{
	"took": 3,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 35,
			"relation": "eq"
		},
		"max_score": 0.026490454,
		"hits": [
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "Owdy94wBoOAS7vbC9TP5",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				}
			},
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "PAdz94wBoOAS7vbCHzPY",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				}
			}
		]
	}
}

复杂查询-分页查询-展示指定字段

请求路径:POST 请求 Url:http://localhost:9200/shopping/_search
请求体参数如下:

{
    "query":{
        "match":{
            "category":"小米"
        }
    },
    "from":0, // 表示起始位置
    "size":2 ,//表示两条
    "_source":["title"] // 规定显示的字段
}

// 返回结果:
{
	"took": 7,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 35,
			"relation": "eq"
		},
		"max_score": 0.026490454,
		"hits": [
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "Owdy94wBoOAS7vbC9TP5",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机"
				}
			},
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "PAdz94wBoOAS7vbCHzPY",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机"
				}
			}
		]
	}
}

根据字段排序查询

通过POST请求:http://localhost:9200/shopping/_search
在请求体参数中添加:

   "sort":{
        "price":{
            "order":"desc"
        }
    }

多条件查询和范围查询

在请求体参数中添加:

{
    "query":{
	    // bool 表示条件的意思
	    "bool":{
            // must 表示 多个条件同时成立 相当于 and
            // should 表示 相当于 or 的意思
              "must":[
               // 条件一
               {
                  // match 表示匹配查询
                   "match":{
                        "category":"小米"
                   }
              },
              // 条件二
               {
                  // match 表示匹配查询
                  "match":{
                    "price":1999.00
                  }
              }
            ],
            // 过滤
            "filter":{
                // 范围
                "range":{
                    // 指定价格字段
                    "price":{
                        // gt大于
                        "gt":1000
                    }
                }
            }
        }
    }
}

全局匹配-完全匹配-高亮显示

{
    "query":{
          //match_phrase : 完全匹配,只能匹配到小米的数据
          // match:全文检索匹配,es会讲检索的词进行分词即小米会拆成 小、 米
          "match_phrase":{
              "category":"小米"
        }
    },
    // 高亮显示
    "highlight":{
         "fields":{
            "category":{}
       }
    }
}

// 查询结果展示
{
	"took": 127,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 35,
			"relation": "eq"
		},
		"max_score": 0.026490454,
		"hits": [
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "Owdy94wBoOAS7vbC9TP5",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				},
				"highlight": {
					"category": [
						// 高亮展示
						"<em>小</em><em>米</em>"
					]
				}
			},
			{
				"_index": "shopping",
				"_type": "_doc",
				"_id": "PQdz94wBoOAS7vbC2DOP",
				"_score": 0.026490454,
				"_source": {
					"title": "小米手机",
					"category": "小米",
					"images": "http://www.gulixueyuan.com/xm.jpg",
					"price": 3999
				},
				"highlight": {
					"category": [
						"<em>小</em><em>米</em>" 
					]
				}
			},
			}

聚合查询

聚合关系-分组排序-平均值

关键字:aggs,其中 terms表示分组 avg表示平均值

在请求体中:

{
    "aggs":{
        // price_group:统计分组的名称,随意起名
        "price_group":{
            // terms 分组排序
            // avg 平均值
            "terms":{
                // 字段
                "field":"price" // 分组字段
            }
        }
    },
     "size":0 // 表示不需要原始数据
}
// 返回结果集:
{
	"took": 22,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 35,
			"relation": "eq"
		},
		"max_score": null,
		"hits": []
	},
	"aggregations": {
		"price_group": {
			"doc_count_error_upper_bound": 0,
			"sum_other_doc_count": 0,
			"buckets": [
				{
					"key": 3999,
					"doc_count": 34
				},
				{
					"key": 1999,
					"doc_count": 1
				}
			]
		}
	}
}

映射关系

创建映射

通过 PUT请求 , /_mapping: 表示映射关系:http://127.0.0.1:9200/people/_mapping

// 请求体参数:
{
    // 配置信息
    "properties":{
        "name":{
            // 类型
            "type":"text", // 表示可以分词
            "index":true, // 表示name字段可以走索引
        },
         "sex":{
            // 类型
            "type":"keyword", // 表示不可以分词
            "index":true, // 表示sex字段可以走索引
        },
         "tel":{
            // 类型
            "type":"text", // 表示可以分词
            "index":false, // 表示tel字段不走索引
        }
    }
}

获取映射关系

GET请求:http://127.0.0.1:9200/people/_mapping
返回内容:

{
	"people": {
		"mappings": {
			"properties": {
				"name": {
					"type": "text"
				},
				"sex": {
					"type": "keyword"
				},
				"tel": {
					"type": "text",
					"index": false
				}
			}
		}
	}
}

测试

分别通过全文查询测试三个字段namesex,tel ,这三个字段分别的含义是:

  • name:支持分词、支持索引
  • sex :不支持分词、支持索引
  • tel :支持分词,不支持索引

name字段测试

可以看到,当我们查询条件只有 小 字时也是可以通过分词查询到正确的结果集的
GET请求http://127.0.0.1:9200/people/_search

{
    "query":{
        // match 全文检索
        "match":{
            // 要查询的字段值
            "name":"小"
        }
    }
}
// 结果集:
{
	"took": 1133,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 1,
			"relation": "eq"
		},
		"max_score": 0.18232156,
		"hits": [
			{
				"_index": "people",
				"_type": "_doc",
				"_id": "1001",
				"_score": 0.18232156,
				"_source": {
					"name": "小米",
					"sex": "男",
					"tel": "1111"
				}
			}
		]
	}
}

sex 字段测试

可以看到,当我们查询条件 不能完全匹配sex字段时时查询不到结果集的。
GET请求http://127.0.0.1:9200/people/_search

{
    "query":{
        // match 全文检索
        "match":{
            // 要查询的字段值
            "sex":"男的"
        }
    }
}
// 结果集:
{
	"took": 4,
	"timed_out": false,
	"_shards": {
		"total": 1,
		"successful": 1,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 0,
			"relation": "eq"
		},
		"max_score": null,
		"hits": []
	}
}

tel字段查询

可以看到,tel字段是不支持索引的,所以在查询时,是查询不到的。
GET请求http://127.0.0.1:9200/people/_search

{
    "query":{
        // match 全文检索
        "match":{
            // 要查询的字段值
            "tel":"1111"
        }
    }
}
// 结果集:
{
	"error": {
		"root_cause": [
			{
				"type": "query_shard_exception",
				"reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
				"index_uuid": "aJinPVJATMCGOsxBCvjOXA",
				"index": "people"
			}
		],
		"type": "search_phase_execution_exception",
		"reason": "all shards failed",
		"phase": "query",
		"grouped": true,
		"failed_shards": [
			{
				"shard": 0,
				"index": "people",
				"node": "psC-jk3hSx6GIVkuAoORKg",
				"reason": {
					"type": "query_shard_exception",
					"reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
					"index_uuid": "aJinPVJATMCGOsxBCvjOXA",
					"index": "people",
					"caused_by": {
						"type": "illegal_argument_exception",
						"reason": "Cannot search on field [tel] since it is not indexed."
					}
				}
			}
		]
	},
	"status": 400
}