ElasticSearch简单查询

无查询条件,只需指定index:

GET /index_name/_search
{
    "query": {
        "match_all": {}
    }
}

分页查询,指定 from 从哪条记录开始,size 指定当前页大小,和 mysql 的 limit m, n 很像,例如:

GET /index_name/_search
{
    "query": {
        "match_all": {}
    },
    "from": 1,
    "size": 2
}

匹配某个项,类似 mysql 的 like ,例如:

POST index_name/_search
{
  "profile": true, 
  "query": {
    "match": {
      "content": "小手机"
    }
  }
}

参数说明:profile 参数为true时,返回查询时的分析信息,比如“小手机”会被解析为“小手”、“手机”并匹配包含这些关键字的记录,如果没有 profile,则只返回匹配到的结果,而不存在分析。

查询结果列表,封装在响应对象的子对象 hits 中,而它是一个类似传统的分页对象,包含了分页信息与记录列表,记录列表默认以匹配度(_score)属性倒叙排序,也就是默认情况下匹配度越高,排在前面。

自定义排序

自定义字段排序,支持多个字段,功能类似sql中的 order by a1 desc, a2 desc… ,因为自定义数据可能为null,一般推荐把 _score 加上

POST index_name/_search
{
  "profile": true, 
  "query": {
    "match": {
      "content": "小手机"
    }
  },
  "sort": [
    {
      "publish_time": {
        "order": "desc"
      }
    },
    {
      "_score":{
        "order": "desc"
      }
    }
  ]
}

限定查询时间

在查询的响应对象中,第一个字段就是 took 字段,表示本次查询占用多少毫秒。

如果我们指定了 timeout 字段限定查询时间为 n 毫秒后,到达该时间还未查询完毕则停止查询并携带已查询到的结果返回。

POST index_name/_search
{
  "profile": true, 
  "query": {
    "match": {
      "content": "手机"
    }
  },
  "timeout": "1ms"
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注