1. 介绍
Elasticsearch也是基于Lucene的全文检索库,本质也是存储数据,很多概念与MySQL类似的。
对比关系:
-
索引(indices)--------------------------------Databases 数据库
-
类型(type)------------------------------------Table 数据表
-
文档(Document)----------------------------Row 行
-
字段(Field)-----------------------------------Columns 列
2. 索引操作
2.1 建立索引
PUT /索引库名
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
}
}
2.2 查询索引
GET demo1
2.3 删除索引
DELETE demo1
2.4 查询索引是否存在
HEAD demo1
3. 映射配置
映射是定义文档的过程,文档包含哪些字段,这些字段是否保存,是否索引,是否分词等
3.1 创建映射
PUT 索引库名/_mapping/类型名
{
"properties": {
"字段名":{
"type": "类型",
"index": true,
"store": false,
"analyzer": "分词器"
}
}
}
3.2 查看映射关系
GET /索引库名/_mapping
4. 增删改
4.1 新增数据,随机生成ID
POST /索引库名/类型名
{
"key": "value"
}
4.2 新增数据,指定ID
POST /索引库名/类型名/id
{
"key": "value"
}
4.3 根据id修改(PUT也可以用于新增)
PUT /索引库名/类型名/3
{
"key": "value"
}
4.4 根据id删除
DELETE 索引库名/类型名/id
5. 查询操作
5.1 查询所有数据
GET _search
{
"query": {
"match_all": {}
}
}
5.2 查询单个索引库所有数据
GET /索引库/_search
{
"query":{
"match_all": {}
}
}
5.3 根据条件查询(分词)
GET /索引库/_search
{
"query":{
"match": {
"字段名": "关键字"
}
}
}
5.4 and查询(不分词)
GET 索引库名/_search
{
"query": {
"match": {
"字段名": {
"query": "关键字",
"operator": "and"
}
}
}
}
5.5 多字段查询
GET 索引库名/_search
{
"query": {
"multi_match": {
"query": "关键字",
"fields": ["字段1", "字段2"]
}
}
}
5.6 词条匹配,查询不分词的字段(除text类型以外的所有类型都是不分词的)
GET 索引库名/_search
{
"query": {
"term": {
"字段名": {
"value": "关键字"
}
}
}
}
5.7 结果过滤(包含),搜索结果只包含这些字段
GET 索引库名/_search
{
"_source": {
"includes": ["字段1", "字段2"]
},
"query": {
"match": {
"字段名": "关键字"
}
}
}
5.8 结果过滤(排除),搜索结果排除这些字段
GET 索引库名/_search
{
"_source": {
"excludes": ["字段1", "字段2"]
},
"query": {
"match": {
"字段名": "关键字"
}
}
}
5.9 模糊查询,有一定的容错性
GET 索引库名/_search
{
"query": {
"fuzzy": {
"字段名": "关键字"
}
}
}
5.10 范围查询
GET 索引库名/_search
{
"query": {
"range": {
"字段名": {
"gte": 1000,
"lte": 3000
}
}
}
}
5.11 布尔查询(must),查询条件需同时成立
GET 索引库名/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"字段1": "关键字"
}
},
{
"range": {
"字段2": {
"gte": 1000
}
}
}
]
}
}
}
5.11 布尔查询(should),查询条件只需满足一个
GET 索引库名/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"字段1": "关键字"
}
},
{
"range": {
"字段2": {
"gte": 1000
}
}
}
]
}
}
}
5.12 布尔查询(must_not),满足条件不查询
GET 索引库名/_search
{
"query": {
"bool": {
"must_not": [
{
"match": {
"字段1": "关键字"
}
},
{
"range": {
"字段2": {
"gte": 1000
}
}
}
]
}
}
}
5.13 布尔查询配合filter,不影响得分
GET 索引库名/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"字段1": "关键字"
}
}
],
"filter": {
"range": {
"字段2": {
"gte": 1000
}
}
}
}
}
}
5.14 查询排序
GET 索引库名/_search
{
"query": {
"match": {
"字段1": "关键字"
}
},
"sort": [
{
"字段2": {
"order": "desc"
}
}
]
}
5.15 分页查询
GET 索引库名/_search
{
"query": {
"match": {
"字段1": "关键字"
}
},
"from": 0,
"size": 20
}
6. 聚合
聚合可以让我们极其方便的实现对数据的统计、分析。
6.1 根据词条聚合
GET 索引库名/_search
{
"size": 0,
"aggs": {
"聚合名称": {
"terms": {
"field": "字段名"
}
}
}
}
6.2 根据词条聚合,并计算平均值
GET 索引库名/_search
{
"size": 0,
"aggs": {
"聚合名称": {
"terms": {
"field": "字段1"
},
"aggs": {
"子聚合名称": {
"avg": {
"field": "字段2"
}
}
}
}
}
}