Elasticsearch文档

一、elasticsearch查询子句:elasticsearch查询子句主要分为叶子子句和混合查询子句,其中term、match等等只能存在于查询json叶子位置的子句为叶子查询子句,像bool、must等等这些可以包含其他查询子句的为混合查询子句。

官网解释:

Elasticsearch provides a full Query DSL based on JSON to define queries. Think of the Query DSL as an AST of queries, consisting of two types of clauses:

Leaf query clauses

Leaf query clauses look for a particular value in a particular field, such as the match, term or range queries. These queries can be used by themselves.

Compound query clauses

Compound query clauses wrap other leaf or compound queries and are used to combine multiple queries in a logical fashion (such as the bool or dis_max query), or to alter their behaviour (such as the constant_score query).

Query clauses behave differently depending on whether they are used in query context or filter context.

二、Query和Filter查询上下文

如果一个查询子句放在query上下文中,那么该子句所关心的是搜索关键字和es中数据的匹配程度,在查询结果中会给出一个匹配score,“How well does this document match this query clause?”。如果一个查询子句放在filter上下文中,那么该子句所关心的是搜索关键字和es中的数据是否可以严格匹配,即匹配就匹配,不匹配就不匹配,不存在“差不多”匹配的说法,“Does this document match this query clause?”。

es 查询 没有文档的字段 es子文档查询_搜索引擎

三、全文匹配

1.match

2.match_phrase

3.match_phrase_prefix

4.multi_match:多字段匹配

GET /_search
{
  "query": {
    "multi_match" : {
      "query":    "this is a test", 
      "fields": [ "subject", "message" ] 
    }
  }
}

四、term和match的区别

match:模糊匹配,需要指定字段名,但是输入会进行分词,比如"hello world"会进行拆分为hello和world,然后匹配,如果字段中包含hello或者world,或者都包含的结果都会被查询出来,也就是说match是一个部分匹配的模糊查询。查询条件相对来说比较宽松。

term: 这种查询和match在有些时候是等价的,比如我们查询单个的词hello,那么会和match查询结果一样,但是如果查询"hello world",结果就相差很大,因为这个输入不会进行分词,就是说查询的时候,是查询字段分词结果中是否有"hello world"的字样,而不是查询字段中包含"hello world"的字样,elasticsearch会对字段内容进行分词,“hello world"会被分成hello和world,不存在"hello world”,因此这里的查询结果会为空。这也是term查询和match的区别。

场景举例:

在es中存在字段 content:hi my name is mafx,在存储时采用standard_analyser,即分词成不同的单词。

当采用term和match搜索‘hi’,‘my’,'name’等等这些单词是均可以搜索出结果,但是当使用term搜索‘my name is mafx’时搜索不出任何结果,因为term不进行分词操作,而库中被分词后不存在这样的短句,因此匹配不到。但是,采用match可以搜索到,因为match会进行分词操作,他会把‘my name is mafx’分词成单词进行匹配。