全文检索-Elasticsearch (三) DSL

DSL:elasticsearch查询语言
elasticsearch对json 的语法有严格的要求,每个json串不能换行,同时一个json串和一个json串之间,必须有一个换行

DSL(介绍查询语言)

下面示例省略了HTTP请求GET /bank/_search

  • 查询所有,按age升序

{
  "query": {
    "match_all": {}
  },
  "sort": {
    "age": "asc"
  },
  "from": 10,
  "size": 10
}

match_all :部分简单指定了我们想去执行的查询类型,意思就是在索引中搜索所有的文档。
sort:指定搜索结果的顺序
size:指定返回的结果数量,size没有指定,它默认为10
from:(从0开始)指定了从哪个文档索引开始

  • match 查询

基本的属性搜索查询(就是通过特定的一个或多个属性来搜索),没有知道哪个索引,全文搜索

查询age为15的文档,且只返回nameage信息

{
   "query":{
      "match" : {
         "age":"15"
      }
   },
   "_source": ["name", "age"]
}

name字段包含小明或者小东的数据

{
  "query": { "match": { "name": "小明 小东" } }
}

name必须包含的文档数据

{
  "query": { "match_phrase": { "name": "小 明" } }
}
  • bool查询

所有addree必须包含milllane

{
  "query": {
    "bool": {
      "must": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}

 所有address属性中包含 “mill”  “lane” 的账户文档

{
  "query": {
    "bool": {
      "should": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}

age属性为40并且state属性为2

{
  "query": {
    "bool": {
      "must": [
        { "match": { "age": "40" } }
      ],
      "must_not": [
        { "match": { "state": "2" } }
      ]
    }
  }
}
  • 过滤

查询年龄大于20小于25的学生

curl -XGET 'localhost:9200/students/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": { "match_all": {} },
      "filter": {
        "range": {
          "age": {
            "gte": 20,
            "lte": 25
          }
        }
      }
    }
  }
}
'

聚合

聚合可以分组并统计数据,类似SQL的GROUP BY操作和SQL的聚合函数;同时聚合可以嵌套

可以返回搜索结果和聚合结果

统计每个年龄断的人数

curl -XGET 'localhost:9200/students/_search?' 
{
"size": 0,#返回0条搜索结果,只返回聚合结果 "aggs": { "group_by_state": { "terms": { "field": "age" } } } }

搜索最小年龄

{
    "size": 0,
   "aggs" : {
      "min_fees" : { "min" : { "field" : "age" } }
   }
}

返回的结果:

{
    "took": 8,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 3,
        "max_score": 0,
        "hits": []
    },
    "aggregations": {
        "min_fees": {
            "value": 12
        }
    }
}
View Code

求年龄总和

{
   "aggs" : {
      "total_fees" : { "sum" : { "field" : "age" } }
   }
}

猜你喜欢

转载自www.cnblogs.com/qiuguochao/p/9080555.html