概念
elasticsearch是一个基于Lucene开发的搜索数据库,提供了restful web接口,es和mysql中的概念对比:
| es | mysql |
|---|---|
| index (索引) | 数据库 |
| type (类型) | 表table |
| document (文档) | 行row |
index
- 创建索引:PUT /customer
- 查看索引:GET /customer
- 删除索引:DELETE /customer
- 查看所有的索引:GET /_cat/indices
- 查找某索引下数据:GET /bank/_search
mapping
创建映射
PUT /index_name
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name": {
"type": "text"
},
"age": {
"type": "integer"
},
"gender": {
"type": "integer"
},
"createTime": {
"type": "date"
}
}
}
}
document
-
在索引中添加文档,格式
/index/type/id,不指定id,ES会自动生成PUT /customer/doc/1 { "name": "John Doe" } -
查看文档
GET /customer/doc/1 -
修改文档
POST /customer/doc/1/_update { "doc": { "name": "Jane Doe" } } -
删除文档
DELETE /customer/doc/1
DSL查询
match_all:查找所有类型
GET /bank/_search
{
"query": {
"match_all": {}
},
"from":0, // 从第几条记录开始
"size": 3, // 查出来多少条
"_source": ["firstname","address"] // 筛选某些字段
}
match:会对检索条件进行分词匹配,并按照评分进行排序
GET /bank/_search
{
"query": {
"match": {
"address": "kings mill" // 忽略大小写
}
}
}
FILED.keyword:address的值必须等于789 Madison Street
GET bank/_search
{
"query": {
"match": {
"address.keyword": "789 Madison Street"
}
}
}
multi_match:city 或 address中包含 kings 或 Ribera,并且在查询过程中,会对于查询条件进行分词
GET /bank/_search
{
"query": {
"multi_match": {
"query": "kings Ribera",
"fields": ["address","city"]
}
}
}
match_phrase:对检索条件不进行分词,作为完整的一个词进行匹配
GET /bank/_search
{
"query": {
"match_phrase": {
"address": "mill road"
}
}
}
bool:组合多个条件
must:gender必须为M,address中必须包含 Kings 或 mill,会进行分词
must_not:age必须不是28
GET bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "gender": "M" } },
{ "match": { "address": "Kings mill"} }
],
"must_not": [
{ "match": { "age": "28" } }
]
}
}
}
should:匹配结果中的firstname字段最好有Cummings,没有也可以,有的话会增加评分
GET bank/_search
{
"query": {
"bool": {
"should": [
{ "match": { "firstname": "Cummings"} }
]
}
}
}
filter:过滤,不会进行相关性得分
GET bank/_search
{
"query": {
"bool": {
"filter": {
"range": { "age": {"gte": 10, "lte": 30} }
}
}
}
}