Elasticsearch聚合查询及排序操作示例

目录
  • 1 es排序
  • 2 match和match的区别
  • 3 分页查询
  • 4 es 组合查询
  • 5 结果过滤展示字端
  • 6 结果高亮展示
  • 7 聚合查询avg、max、min、sum、分组
  • 8 mapping和_template模版
  • 9 ik分词
  • 10 term和match的区别

1 es排序

# 1 排序
GET jeff/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
   "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ]
}
# 升序
GET jeff/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
   "sort": [
    {
      "age": {
        "order": "asc"
      }
    }
  ]
}
# 并不是所有类型都支持排序(只允许数字类型做排序)
GET jeff/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
   "sort": [
    {
      "name": {
        "order": "asc"
      }
    }
  ]
}

2 match和match的区别

# match和match_all的区别?
mach表示要查询,根据字段查,match_all查所有
GET jeff/doc/_search
{
  "query": {
    "match_all": {}
  }
}

3 分页查询

GET jeff/doc/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ],
  "from": 2,
  "size": 1
}
#   "from": 2,代表从第二条开始, 取一条"size": 1
# 有了这个查询,如何分页?
一页有10条数据
第一页:
  "from": 0,
  "size": 10
第二页:
  "from": 10,
  "size": 10
第三页:
  "from": 20,
  "size": 10

4 es 组合查询

# 多个条件,and ,or ,not
# 对到es中就是布尔查询,must,should,must_not,filter
must  ---  and
should --- or
must_not --- not
filter --- 过滤
# 1 组合查询之must
# 查询form gu和age=30的数据
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "from": "gu"
          }
        },
        {
          "match": {
            "age": "30"
          }
        }
      ]
    }
  }
}
# 查询form gu数据()
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "from": "gu"
          }
        }
      ]
    }
  }
}
# 同上
GET gyy/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  }
}
# 2 组合查询之should,或者的条件
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "from": "gu"
          }
        },
        {
          "match": {
            "tags": "闭月"
          }
        }
      ]
    }
  }
}
# 3 组合查询之must_not  取反
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "from": "gu"
          }
        },
        {
          "match": {
            "tags": "可爱"
          }
        },
        {
          "match": {
            "age": 18
          }
        }
      ]
    }
  }
}
# `filter`条件过滤查询,过滤条件的范围用`range`表示,`gt`表示大于,大于多少呢
# gt:大于   lt:小于  get:大于等于   let:小于等于
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "from": "gu"
          }
        }
      ],
      "filter": {
        "range": {
          "age": {
            "gt": 25
          }
        }
      }
    }
  }
}
# 查询年龄小于等于18的所有数据
GET gyy/doc/_search
{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "age": {
            "lte": 18
          }
        }
      }
    }
  }
}

5 结果过滤展示字端

# 对结果进行过滤,类似于如下
select * from user;
select name,age from user;
# 对应到es的查询
GET gyy/doc/_search
{
  "query": {
    "match": {
      "name": "顾老二"
    }
  },
  "_source": ["name", "age"]
}

6 结果高亮展示

# 3 结果高亮显示(默认情况)
GET gyy/doc/_search
{
  "query": {
    "match": {
      "name": "石头"
    }
  },
  "highlight": {
    "fields": {
      "name": {}
    }
  }
}
# 定制高亮显示的样式
GET gyy/chengyuan/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
  "highlight": {
    "pre_tags": "<b class='key' style='color:red'>",
    "post_tags": "</b>",
    "fields": {
      "from": {}
    }
  }
}

小结:

混合开发,你知道怎么处理

前后端分离,你怎么处理?

<b class='key' style='color:red'>串直接以josn格式返回,前端自行渲染

用的最多就是match+布尔+高亮+分页

7 聚合查询avg、max、min、sum、分组

# 聚合查询
# 1 聚合查询之avg
select max(age) as my_avg from user;
GET gyy/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
  "aggs": {
    "my_avg": {
      "avg": {
        "field": "age"
      }
    }
  },
  "_source": ["name", "age"]
}
# 2 聚合查询之max,size=0表示不取数据,只要max的结果
GET gyy/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
  "aggs": {
    "my_max": {
      "max": {
        "field": "age"
      }
    }
  },
  "size": 0
}
# 3 聚合之min
GET gyy/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
  "aggs": {
    "my_min": {
      "min": {
        "field": "age"
      }
    }
  },
  "size": 0
}
# 4 聚合查询之sum
GET gyy/doc/_search
{
  "query": {
    "match": {
      "from": "gu"
    }
  },
  "aggs": {
    "my_sum": {
      "sum": {
        "field": "age"
      }
    }
  },
  "size": 0
}
# 5 聚合之分组
GET gyy/doc/_search
{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "age_group": {
      "range": {
        "field": "age",
        "ranges": [
          {
            "from": 15,
            "to": 20
          },
          {
            "from": 20,
            "to": 25
          },
          {
            "from": 25,
            "to": 30
          }
        ]
      }
    }
  }
}

8 mapping和_template模版

GET _template/user_instagram  # 查看模版
PUT _template/user_instagram  # 修改模版
{跟字段信息数据}
GET user_instagram/_mapping  # 查看索引信息
PUT user_instagram/_mapping  # 修改索引信息
{跟字段信息数据}

模版中如果有name字段,存的时候会在索引中自动匹配

模版中如果没有age字段,存的时候索引找不到字段,存不进去。

需要现在模版中添加字段,再到索引中添加字段,索引生成之后需要手动添加字段,不会自动生成

# 查看索引信息---》mapping字典---》映射(类型,表类型,表结构)
GET user_instagram/_mapping
# 6.x以后一个索引只能有一个映射类型(只能有一个表)
# 创建映射
# 创建索引,并设置映射
PUT _template/user_instagram
{
    "order" : 1,
    "index_patterns" : [
      "user_instagram-v1_0"
    ],
    "settings" : {
      "index" : {
        "default_pipeline" : "auto_timestamp_pipeline",
        "mapping" : {
          "total_fields" : {
            "limit" : "10000"
          }
        },
        "refresh_interval" : "600s",
        "number_of_shards" : "8",
        "number_of_replicas" : "0",
        "max_inner_result_window" : "50000"
      }
    },
    "mappings" : {
      "_meta" : {
        "software_version_mapping" : "1.0"
      },
      "dynamic" : "strict",
      "properties" : {
        "is_private" : {
          "type" : "boolean"
        },
        "full_name" : {
          "type" : "text"
        },
        "create_time" : {
          "type" : "date"
        },
        "avatar_url" : {
          "type" : "text"
        },
        "user_id" : {
          "eager_global_ordinals" : true,
          "type" : "keyword"
        },
        "follower_num" : {
          "type" : "integer"
        },
        "following_num" : {
          "type" : "integer"
        },
        "post_count" : {
          "type" : "integer"
        },
        "nickname" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "ignore_above" : 256,
              "type" : "keyword"
            }
          },
          "doc_values" : false
        },
        "requested_by_viewer" : {
          "type" : "boolean"
        },
        "is_verified" : {
          "type" : "boolean"
        },
        "followed_by_viewer" : {
          "type" : "boolean"
        }
      }
    },
    "aliases" : {
      "user_instagram" : { }
    }
  }
# 插入测试数据
PUT books/_doc/1
{
  "title":"大头儿子小偷爸爸",
  "price":100,
  "addr":"北京天安门",
  "company":{
    "name":"我爱北京天安门",
    "company_addr":"我的家在东北松花江傻姑娘",
    "employee_count":10
  },
  "publish_date":"2019-08-19"
}
PUT books/_doc/2
{
  "title":"白雪公主和十个小矮人",
  "price":"99",
  "addr":"黑暗森里",
  "company":{
    "name":"我的家乡在上海",
    "company_addr":"朋友一生一起走",
    "employee_count":10
  },
  "publish_date":"2018-05-19"
}
PUT books/_doc/3
{
  "title":"白雪公主和十个小矮人",
  "price":"99",
  "addr":"黑暗森里",
  "age":18
}
# 查看映射
GET books
GET books/_mapping

映射是什么?映射有什么用?  规定了表结构(不是强制的),规定了哪个字段是可以用来全文检索,是否是数字类型,布尔类型

mapping类型一旦确定,以后就不能修改了,但是可以插入字段

9 ik分词

# 全文检索,有了映射,决定了我可以对某个字段做全文检索
# es默认分词对英文友好,使用中文分词器(es的插件),ik(作者,中国人,elasticsearch开源社区负责人)
# 是es的一个插件(es如何安装插件)
#第一种:命令行(内置插件)
  	bin/elasticsearch-plugin install analysis-smartcn  安装中文分词器
#第二种:url安装(第三方插件)
  	bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.5.0/elasticsearch-analysis-ik-7.5.0.zip
#第三种:手动安装(推荐用)
  #下载,解压到es的plugins路径下,重启es即可
  #注意:ik分词器跟es版本一定要对应
# 两种分词方式
  # ik_smart:分词分的
  # ik_max_word :分词分的多
  # ik_smart分的词少,粒度大
  GET _analyze
  {
    "analyzer": "ik_smart",
    "text": "上海自来水来自海上"
  }
  # ik_smart分的词多,粒度小
  GET _analyze
  {
    "analyzer": "ik_max_word",
    "text": "上海自来水来自海上"
  }
# 在创建映射的时候配置
# 以后你的操作:
#文章标题:ik_max_word
#文章内容:ik_smart
#摘要
#作者
#创建时间

10 term和match的区别

# match:我们今天出去玩 ----》分词---》按分词去搜
#term:我们今天出去玩---》直接拿着[我们今天出去玩]---&gt;去索引中查询
# 查不到内容,直接拿着  Python爬虫 去查,因为没有索引,所以查不到
GET books/_search
{
  "query":{
    "term":{
      "title":"Python爬虫"
    }
  }
}
# 能查到,而且带python的都查出来了
# Python   爬虫  分了词,分别拿着这两个词去查,带python关键字,带爬虫关键字都能查到
GET books/_search
{
  "query":{
    "match":{
      "title":"Python爬虫"
    }
  }
}

以上就是Elasticsearch聚合查询及排序操作示例的详细内容,更多关于Elasticsearch聚合查询及排序的资料请关注我们其它相关文章!

(0)

相关推荐

  • java使用elasticsearch分组进行聚合查询过程解析

    这篇文章主要介绍了java使用elasticsearch分组进行聚合查询过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 java连接elasticsearch 进行聚合查询进行相应操作 一:对单个字段进行分组求和 1.表结构图片: 根据任务id分组,分别统计出每个任务id下有多少个文字标题 1.SQL:select id, count(*) as sum from task group by taskid; java ES连接工具类 p

  • elasticsearch python 查询的两种方法

    elasticsearch python 查询的两种方法,具体内容如下所述: from elasticsearch import Elasticsearch es = Elasticsearch res1 = es.search(index="2018-07-31", body={"query": {"match_all": {}}}) print(es1) {'_shards': {'failed': 0, 'skipped': 0, 'suc

  • Elasticsearch QueryBuilder简单查询实现解析

    elasticsearch中存储的全部文档 1.matchAllQuery() matchAllQuery()方法用来匹配全部文档 public class QueryTest { public static void main(String[] args) { //创建对象,设置集群名称和IP地址 ElasticsearchUtils es = new ElasticsearchUtils("im_shan", "localhost"); String index

  • Python-ElasticSearch搜索查询的讲解

    Elasticsearch 是一个开源的搜索引擎,建立在一个全文搜索引擎库 Apache Lucene™ 基础之上. Lucene 可能是目前存在的,不论开源还是私有的,拥有最先进,高性能和全功能搜索引擎功能的库.但是 Lucene 仅仅只是一个库.为了利用它,你需要编写 Java 程序,并在你的 java 程序里面直接集成 Lucene 包. 更坏的情况是,你需要对信息检索有一定程度的理解才能明白 Lucene 是怎么工作的.Lucene 是 很 复杂的. 在上一篇文章中介绍了ElasticS

  • elasticsearch kibana简单查询讲解

    一.简单的CRUD操作 1.添加 PUT /index/type/id { "json数据" } 2.查询 GET /index/type/id 3.修改 POST /index/type/id/_update { "doc": { "FIELD": "值" } } 4.删除 DELETE /index/type/id 二.搜索 搜索可以分成六大类 1.query string search 2.query DSL 3.que

  • java 通过聚合查询实现elasticsearch的group by后的数量

    通过聚合查询获取group by 后的数量 /** * 获取key的个数 * * @param key 要group by的字段名 * @param index 索引名称 * @return id的个数 */ public static int getKeyCount(String key, String index) { int count = 0; TransportClient client = null; try { client = connectionPool.getConnecti

  • Elasticsearch聚合查询及排序操作示例

    目录 1 es排序 2 match和match的区别 3 分页查询 4 es 组合查询 5 结果过滤展示字端 6 结果高亮展示 7 聚合查询avg.max.min.sum.分组 8 mapping和_template模版 9 ik分词 10 term和match的区别 1 es排序 # 1 排序 GET jeff/doc/_search { "query": { "match": { "from": "gu" } }, &qu

  • Elasticsearch的删除映射类型操作示例

    目录 一 前言 二 什么是映射类型? 三 为什么要删除映射类型? 四 映射类型的替代方法 4.1 将映射类型分开存储在索引中 4.2 自定义类型字段回到顶部 五 没有映射类型的父/子 六 删除映射类型的计划 七将多类型索引迁移到单一类型 7.1 每种文档类型的索引 7.2 自定义类型字段 八 总结 一 前言 官方解释:https://www.elastic.co/guide/en/elasticsearch/reference/6.0/removal-of-types.html 在elastic

  • PHP中使用jQuery+Ajax实现分页查询多功能操作(示例讲解)

    1.首先做主页面Ajax_pag.php 代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ajax做分页</title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="Ajax_

  • Laravel框架查询构造器 CURD操作示例

    本文实例讲述了Laravel框架查询构造器 CURD操作.分享给大家供大家参考,具体如下: 新增 //插入一条数据 public function insert(){ $rs = DB::table('student')->insert([ 'name' => 'Kit', 'age' => 12 ]); dd($rs); //true } //插入一条数据并返回自增ID public function insert(){ $id = DB::table('student')->i

  • JS实现json对象数组按对象属性排序操作示例

    本文实例讲述了JS实现json对象数组按对象属性排序操作.分享给大家供大家参考,具体如下: 在实际工作经常会出现这样一个问题:后台返回一个数组中有i个json数据,需要我们根据json中某一项进行数组的排序. 例如返回的数据结构大概是这样: { result:[ {id:1,name:'中国银行'}, {id:3,name:'北京银行'}, {id:2,name:'河北银行'}, {id:10,name:'保定银行'}, {id:7,name:'涞水银行'} ] } 现在我们根据业务需要,要根据

  • Python实现针对json中某个关键字段进行排序操作示例

    本文实例讲述了Python实现针对json中某个关键字段进行排序操作.分享给大家供大家参考,具体如下: 示例: json_array = [{"time":20150312,"value":"c"}, {"time":20150301,"value":"a"}, {"time":20150305,"value":"b"}] js

  • JS实现简单表格排序操作示例

    本文实例讲述了JS实现简单表格排序操作.分享给大家供大家参考,具体如下: <!DOCTYPE> <html> <head> <meta http-equiv="Content-type" content="text/html" charset="utf-8"> <title>sort table</title> <style> *{ margin:0px; pad

  • JavaScript基于对象方法实现数组去重及排序操作示例

    本文实例讲述了JavaScript基于对象方法实现数组去重及排序操作.分享给大家供大家参考,具体如下: <script> //用对象方法实现数组去重 Array.prototype.unique = function() { var newArr = []; for (var i = 0; i < this.length; i++) { if(newArr.indexOf(this[i]) == -1){ newArr.push(this[i]); } } return newArr;

  • Python实现的字典排序操作示例【按键名key与键值value排序】

    本文实例讲述了Python实现的字典排序操作.分享给大家供大家参考,具体如下: 对字典进行排序?这其实是一个伪命题,搞清楚python字典的定义---字典本身默认以key的字符顺序输出显示---就像我们用的真实的字典一样,按照abcd字母的顺序排列,并且本质上各自没有先后关系,是一个哈希表的结构: 但实际应用中我们确实有这种排序的"需求"-----按照values的值"排序"输出,或者按照别的奇怪的顺序进行输出,我们只需要把字典转化成list或者tuple,把字典每

  • Java实现对字符串中的数值进行排序操作示例

    本文实例讲述了Java实现对字符串中的数值进行排序操作.分享给大家供大家参考,具体如下: 问题: 对"34 9 -7 12 67 25"这个字符串中的数值从小到大排序! 解决方法: 先介绍几个eclipse快捷键:输入for再按下"alt+/"可快速写一个for循环 选中某一个小写单词 Ctrl+Shift+x  可变大写,选中某一个大写单词 Ctrl+Shift+y  可变小写 下面请看具体实现代码: import java.util.Arrays; public

随机推荐