• Elasticsearch查询


    Elasticsearch查询

    什么是Elasticsearch?

    Elasticsearch is a real-time, distributed storage, search, and analytics engine

    Elasticsearch 是一个实时分布式存储、搜索、分析的引擎。

    介绍那儿有几个关键字:

    • 实时

    • 分布式

    • 搜索

    • 分析

    于是我们就得知道Elasticsearch是怎么做到实时的,Elasticsearch的架构是怎么样的(分布式)。存储、搜索和分析(得知道Elasticsearch是怎么存储、搜索和分析的)

    为什么要用Elasticsearch

    在学习一项技术之前,必须先要了解为什么要使用这项技术。所以,为什么要使用Elasticsearch呢?我们在日常开发中,数据库也能做到(实时、存储、搜索、分析)。

    相对于数据库,Elasticsearch的强大之处就是可以模糊查询

    有的同学可能就会说:我数据库怎么就不能模糊查询了??我反手就给你写一个SQL:

    select * from user where name like '%爱国%'

    的确,这样做的确可以。但是要明白的是:name like %Java3y%这类的查询是不走索引的,不走索引意味着:只要你的数据库的量很大(1亿条),你的查询肯定会是级别的

    如果对数据库索引还不是很了解的同学,建议复看一下我以前的文章。我觉得我当时写得还不赖(哈哈哈) GitHub搜关键字:”索引“

    而且,即便给你从数据库根据模糊匹配查出相应的记录了,那往往会返回大量的数据给你,往往你需要的数据量并没有这么多,可能50条记录就足够了。

    还有一个就是:用户输入的内容往往并没有这么的精确,比如我从Google输入ElastcSeach(打错字),但是Google还是能估算我想输入的是Elasticsearch

    而Elasticsearch是专门做搜索的,就是为了解决上面所讲的问题而生的,换句话说:

    • Elasticsearch对模糊搜索非常擅长(搜索速度很快)

    • 从Elasticsearch搜索到的数据可以根据评分过滤掉大部分的,只要返回评分高的给用户就好了(原生就支持排序)

    • 没有那么准确的关键字也能搜出相关的结果(能匹配有相关性的记录)

    Elasticsearch的数据结构

    众所周知,你要在查询的时候花得更少的时间,你就需要知道他的底层数据结构是怎么样的;举个例子:

    • 树型的查找时间复杂度一般是O(logn)

    • 链表的查找时间复杂度一般是O(n)

    • 哈希表的查找时间复杂度一般是O(1)

    • ….不同的数据结构所花的时间往往不一样,你想要查找的时候要,就需要有底层的数据结构支持

    从上面说Elasticsearch的模糊查询速度很快,那Elasticsearch的底层数据结构是什么呢?我们来看看。

    我们根据“完整的条件”查找一条记录叫做正向索引;我们一本书的章节目录就是正向索引,通过章节名称就找到对应的页码。

    首先我们得知道为什么Elasticsearch为什么可以实现快速的“模糊匹配”/“相关性查询”,实际上是你写入数据到Elasticsearch的时候会进行分词

    Elasticsearch的术语和架构

    从官网的介绍我们已经知道Elasticsearch是分布式存储的,如果看过我的文章的同学,对分布式这个概念应该不陌生了。

    在讲解Elasticsearch的架构之前,首先我们得了解一下Elasticsearch的一些常见术语。

    • Index:Elasticsearch的Index相当于数据库的Table

    • Type:这个在新的Elasticsearch版本已经废除(在以前的Elasticsearch版本,一个Index下支持多个Type--有点类似于消息队列一个topic下多个group的概念)

    • Document:Document相当于数据库的一行记录

    • Field:相当于数据库的Column的概念

    • Mapping:相当于数据库的Schema的概念

    • DSL:相当于数据库的SQL(给我们读取Elasticsearch数据的API)

    • Elasticsearch 写入的流程

      上面我们已经知道当我们向Elasticsearch写入数据的时候,是写到主分片上的,我们可以了解更多的细节。

      客户端写入一条数据,到Elasticsearch集群里边就是由节点来处理这次请求:

       

       

    集群上的每个节点都是coordinating node协调节点),协调节点表明这个节点可以做路由。比如节点1接收到了请求,但发现这个请求的数据应该是由节点2处理(因为主分片在节点2上),所以会把请求转发到节点2上。

    • coodinate(协调)节点通过hash算法可以计算出是在哪个主分片上,然后路由到对应的节点

    • shard = hash(document_id) % (num_of_primary_shards)

    路由到对应的节点以及对应的主分片时,会做以下的事:

    1. 将数据写到内存缓存区

    2. 然后将数据写到translog缓存区

    3. 每隔1s数据从buffer中refresh到FileSystemCache中,生成segment文件,一旦生成segment文件,就能通过索引查询到了

    4. refresh完,memory buffer就清空了。

    5. 每隔5s中,translog 从buffer flush到磁盘中

    6. 定期/定量从FileSystemCache中,结合translog内容flush index到磁盘中。

     

    Elasticsearch基本查询

    1、简单查询

    GET lib3/user/_search
    {
     "query":{
       "match_all": {}
    }
    }



    get lib3/user/_search
    {
     "query":{
       "match_all": {}
    },
     "_source":{
        "includes": "addr*",
        "excludes": ["name","bir*"]
    }
    }

    2、控制查询返回的数量

    get lib3/user/_search
    {
     "from":0,
     "size":2,
     "query":{
       "terms":{
         "interests": ["changge","tiaowu"]
      }
    }
    }

    3、排序

    前缀匹配查询"match_phrase_prefix", 并使用sort实现排序:desc:降序,asc升序

    GET /lib3/user/_search
    {
       "query": {
           "match_phrase_prefix": {
             "interests": "you"
          }
      },
       
       "sort":[
        {
           "age":{"order": "desc"}
        }
        ]
    }

    4、范围查询

    range:实现范围查询

    参数:from,to,include_lower,include_upper,boost

    include_lower:是否包含范围的左边界,默认是true

    include_upper:是否包含范围的右边界,默认是true

    GET /lib3/user/_search
    {
       "query": {
           "range": {
               "birthday": {
                   "from": "1990-10-10",
                   "to": "2000-05-01",
                    "include_lower": true,
                   "include_upper": false
              }
          }
      }
    }


    GET /lib3/user/_search
    {
       "query": {
           "range": {
               "age": {
                   "from": 18,
                   "to": 25,
                   "include_lower": true,
                   "include_upper": false
              }
          }
      }
    }

    5、fuzzy实现模糊查询

    fuzzy 查询是 term 查询的模糊等价。

    GET /lib3/user/_search
    {
       "query": {
           "fuzzy": {
                "interests": "chagge"
          }
      }
    }

    GET /lib3/user/_search
    {
       "query": {
           "fuzzy": {
                "interests": {
                    "value": "chagge"
                }
          }
      }
    }

    6、指定返回的字段

    get lib3/user/_search
    {
     "_source":["name","age"],
     "query":{
       "match": {
         "interests": "changge"
      }
    }
    }

    7、显示要的字段、去除不需要的字段、可以使用通配符*

    get lib3/user/_search
    {
     "query":{
       "match_all": {}
    },
     "_source":{
        "includes": "addr*",
        "excludes": ["name","bir*"]
    }
    }

    8、多条件查询

    {

     "query": {

       "bool": {

         "must":[

    {"match":{"title":"战"}},

    {"match":{"content":"星球"}}

    ]

      }

    }

    }

    must_not使用

    内容里不含有“武士”

    {

     "query": {

       "bool": {

         "must":{"match":{"title":"战"}},

         "must_not":{"match":{"content":"武士"}}

      }

    }

    }

    Elasticsearch 组合查询

    group by
    == sql
    select src_ip,count(*) as x from attack_log where timestamp > 1627747200000 and timestamp < 1629104108000 group by src_ip order by x desc limit 5;

    例子

    GET attack_log/_search
    {
     "size":0,
     "query": {
       "bool": {
         "filter": [
          {
             "range": {
               "timestamp": {
                 "gt": "1627747200000",
                 "lt": "1629104108000"
              }
            }
          }
        ]
      }
    },
     "aggs": {
       "group_by": {
         "terms": {
           "field": "src_ip.keyword",
           "size":5,
           "order": {
             "_count": "desc"
          }
        }
      }
    }
    }

    返回示例

    {
     "took" : 2,
     "timed_out" : false,
     "_shards" : {
       "total" : 3,
       "successful" : 3,
       "skipped" : 0,
       "failed" : 0
    },
     "hits" : {
       "total" : 316,
       "max_score" : 0.0,
       "hits" : [ ]
    },
     "aggregations" : {
       "group_by" : {
         "doc_count_error_upper_bound" : 0,
         "sum_other_doc_count" : 18,
         "buckets" : [
          {
             "key" : "1.1.1.1",
             "doc_count" : 99
          },
          {
             "key" : "1.1.1.4",
             "doc_count" : 62
          },
          {
             "key" : "1.1.1.7",
             "doc_count" : 59
          },
          {
             "key" : "1.1.1.6",
             "doc_count" : 49
          },
          {
             "key" : "1.1.1.8",
             "doc_count" : 29
          }
        ]
      }
    }
    }

    组合查询

    GET /analysis/_search
    {
     "_source": {   ---SELECT
       "includes": ["fileName","starttime","duration","repNo","repGroup","typeOfService"],
       "excludes": ["blankKeyword","keyword","topicHitDetail"]
    },
     "query": {   ---WHERE
       "bool": {
         "filter": {
           "term": {
             "typeOfService": "转账"
          }
        }
      }
    },
     "aggs": {  ---GROUP BY
       "class_buckets": {  ---HAVING
         "filter": {
           "range": {
             "duration": {
               "gte": 600
            }
          }
        },
         "aggs": {
           "class_count": {
             "terms": {
               "field": "classfication_f"
            },
             "aggs": {
               "count": {
                 "value_count": {
                   "field": "classfication_f"
                }
              },
               "count_filter":{
                 "bucket_selector": { ------HAVING
                   "buckets_path": {
                     "count":"count"
                  },
                   "script": "params.count>=1000"
                }
              }
            }
          }
        }
      }
    },
     "from": 0, ---LIMIT
     "size": 10,
     "sort": [    ---ORDER BY
      {
         "starttime": {
           "order": "desc"
        }
      }
    ]
    }

    elasticsearch 关于index

    index概念包括:

    1、写入的数据(API等方式)

    2、es里面的索引数据

    3、lucene索引

    segmant-shard-index

     

  • 相关阅读:
    ubuntu中:configure: error: curses development files not found
    configure: error: liblzma development files not found
    Ubuntu中 configure: WARNING: libcurl not enabled: library not found
    ubuntu中如何查看系统已经安装了哪些包
    ./popins2: error while loading shared libraries: libbifrost.so: cannot open shared object file: No such file or directory
    ubuntu中:configure: WARNING: S3 support not enabled: requires SSL development files
    VueReactAngular三者区别
    阿里云物联网IOT
    阿里云混合云
    阿里云企业服务和云通信
  • 原文地址:https://www.cnblogs.com/Gaimo/p/16098171.html
Copyright © 2020-2023  润新知