ElasticSearch/ES
Elasticsearch(存储+检索+分析),简称ES
ES数据模型:
Index:索引,由多个document组成;索引名必须为小写
Type:索引类型,ES6中一个index只能有一个type,ES7中取消了type的概念
Document:文档,由多个field组成
Field:字段
ES数据模型与Mysql相对比:
Document(文档):
示例:
_index:索引为movie_index2,可以理解为库名是movie_index2
_type:类型为movie,可以理解成表名是movie
_id:id为1
_version:文档版本号,上述代表修改了6次
_score:在搜索结果中的评分,上述未涉及到
_source:这里面的内容就是数据,该数据有3个field,分别为name,age,sex
ES中的操作一般为POT/POST/DELETE/GET
DELETE:删除
#删除索引moive_index2中,id为3的document
DELETE /moive_index2/movie/3
#删除索引moive_index2
DELETE /moive_index2
PUT:更新或创建
#创建索引为test,type为stu,id为1
PUT test/stu/1
{
"name":"小韩",
"age":18,
"sex":"男"
}
备注:这里使用POST也可以进行创建
#如果想对id为1中的数据进行修改,可以直接覆盖;
#年龄改为19
PUT test/stu/1
{
"name":"小韩",
"age":19,
"sex":"男"
}
备注:如果使用以下代码,会把id为1中的数据直接覆盖,只剩下一个age字段
PUT test/stu/1
{
"age":19
}
所以,如果想对某个字段进行修改,可以使用POST
POST:创建
#对age和sex字段值进行更新
POST /test/stu/1/_update
{
"doc": {
"age":19,
"sex":"女"
}
}
备注:使用update需要有doc或者script
GET:查看
1、查询全部数据:match_all
GET /test/stu/_search
或者
GET /test/stu/_search
{
"query": {
"match_all": {}
}
}
2、查询指定id数据:
GET /test/stu/1
3、match:分词结果为han和zu两个单词,只要name字段值中包含有其中任意一个,那么返回该文档
GET test/stu/_search
{
"query": {
"match": {
"name": "han zu"
}
}
}
4、match_phrase:字段值必须依次匹配所有分词,且位置也要一致
GET test/stu/_search
{
"query": {
"match_phrase": {
"name": "小韩"
}
}
}
5、multi_match:多字段匹配查询,字段name或interest中有music或 Newton
GET def/stu/_search
{
"query": {
"multi_match": {
"query": "music Newton",
"fields": ["name","interest"]
}
}
}
6、term
7、Terms
8、range:查询字段year的值大于等于1000,小于等于2000的文档
GET def/stu/_search
{
"query": {
"range": {
"year": {
"gte": 1000,
"lte": 2000
}
}
}
}
9、bool:查询name中包含john,interest包含boxing,classOf>=2016
GET def/stu/_search
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "boxing john",
"fields": ["name","interest"]
}
},
{
"range": {
"classOf": {
"gt": 2016
}
}
}
]
}
}
}
10、from+size浅分页,取出所有文档的前2条,偏移从0开始;类似于Mysql中的limit
GET def/stu/_search
{
"query": {
"match_all": {}
},
"size": 2,
"from": 0
}
11、批量操作
语法:
PUT _bulk
{"index/create/update/delete":{"_index":"...","_type":"...","_id":"..."}}
{"field1":"value1",……}
示例:批量增加数据
PUT /_bulk
{"create":{"_index":"def","_type":"stu","_id":"2"}}
{"id": 2, "name": "Isaac Newton", "major":"Physics", "interest": "novel, soccer, cooking"}
{"create":{"_index":"def","_type":"stu","_id":"3"}}
{"id": 3, "name": "John Kennedy", "major":"Politics","interest": "talking, dating, boxing"}
备注:一条语句要写在一行!!!!