- _search/查询:
- timed_out设置超时时间:
- highlight高亮搜索:
- _mapping查看类型映射:
- aggs聚合统计:
- aggs多个聚合:
- op_type插入已存在数据返回错误信息:
- version外部版本号控制乐观并发:
- _mget取多个文档
- _bulk批量操作
- multi_match多字段执行相同match 查询:
- range 查询指定区间:
- term 查询
- exists查询
- bool 查询
- constant_score 查询:
- validate-query验证查询是否合法:
- explain查询不合法的原因:
- sort排序:
- sort多级排序:
- consistency一致性:
- size&from分页:
- 分析器
- 内置分析器
- type简单域类型
- index控制索引
- analyze查看文本分析:
- refresh API:
- flush API:
- 提高精度
- boost权重:
- indices_boost:
- boosting 查询:
- dis_max查询:
- tie_breaker:
- 模糊匹配:
- 使用
^字符为单个字段提升权重: - copy_to:
cross_fields跨字段查询:match_phrase短语匹配:slop查询词条相隔多远时仍然能将文档视为匹配:position_increment_gap增加当前词条position的指定值:shingles提高相关度评分:wildcard通配符查询:regexp正则式查询:match_phrase_prefix输入即搜索:- index_options词频:
- idf逆向文档频率:
- norm字段长度归一值:
- function_score、field_value_factor相关度排序依据:
- modifier受欢迎度:
- factor受欢迎程度:
- boost_mode函数:
- max_boost限制函数的最大效果:
- weight过滤提成权重:
- 配置BM25相似度算法:
- terms 桶操作:
- aggs聚合嵌套:
- 条形图统计:
- extended_stats计算:
- date_histogram时间统计:
- 返回空buckets:
- post_filter 过滤搜索结果:
- 排序:
- cardinality去重:
_search/查询:
GET /_search/{"took" : 7, //执行整个搜索请求耗费了多少毫秒"timed_out" : false, //查询是否超时"_shards" : {"total" : 7, //查询中参与分片的总数"successful" : 7,"skipped" : 0,"failed" : 0},"hits" : { //查询结果的前十个文档"total" : {"value" : 10000, //匹配到的文档总数"relation" : "gte"},"max_score" : 1.0, //查询所匹配文档的 _score 的最大值"hits" : [{"_index" : "test","_type" : "_doc","_id" : "3","_score" : 1.0, //文档与查询的匹配程度"_source" : {"name" : "wangwu","age" : 25,"gender" : "women","birthday" : "2000-10-10"},{...}]}}查询last_name为Smith的文档GET /megacorp/_search?q=last_name:Smith&prettyGET /megacorp/_search{"query": {"match": {"last_name": "Smith"}}}查询last_name为Smith,age大于等于10小于等于30的文档GET /megacorp/_search{"query": {"bool": {"must": [{"match": {"last_name": "smith"}}],"filter": {"range": {"age": {"gte": 10,"lte": 30}}}}}}
/_search
/gb/_search
/gb,us/_search
/g,u/_search
timed_out设置超时时间:
GET /_search?timeout=10ms
在请求超时之前,Elasticsearch 将会返回已经成功从每个分片获取的结果。
应当注意的是 timeout 不是停止执行查询,它仅仅是告知正在协调的节点返回到目前为止收集的结果并且关闭连接。在后台,其他的分片可能仍在执行查询即使是结果已经被发送了。
使用超时是因为 SLA(服务等级协议)对你是很重要的,而不是因为想去中止长时间运行的查询。
highlight高亮搜索:
GET /megacorp/_search{"query": {"match_phrase": {"about": "rock"}},"highlight": {"fields": {"about": {}}}}
_mapping查看类型映射:
GET /.test/_mapping设置预加载以便interests使用聚合查询不用加上.keyword:PUT /employee/_mapping{"properties":{"interests":{"type":"text","fielddata":true}}}
aggs聚合统计:
interests字段出现次数排名GET /employee/_search?pretty{"aggs": {"all_interests": {"terms": { "field": "interests" }}}}聚合统计last_name为Smith的索引,interests字段出现次数排名GET /megacorp/_search{"query": {"match": {"last_name": "smith"}},"size": 0 ,"aggs": {"all_interests": {"terms": {"field": "interests.keyword","size": 10}}}}
aggs多个聚合:
GET /megacorp/_search{"size": 0,"aggs": {"all_interests": {"terms": {"field": "interests.keyword"},"aggs": {"avg_avg": {"avg": {"field": "age"}}}}}}
op_type插入已存在数据返回错误信息:
PUT /website/_doc/126?op_type=createPUT /website/_doc/126/_create
version外部版本号控制乐观并发:
PUT /website/_doc/123?version=10&version_type=external{"title": "My first blog entry","text": "Starting to get the hang of this..."}
_mget取多个文档
不同索引写法:
GET /_mget{"docs":[{"_index":"website","_id":124},{"_index":"website","_id":1,"_source":"text"}]}
相同索引写法:
GET /website/_mget{"docs":[{"_id":124},{"_id":1}]}
通过id查询
GET /website/_mget{"ids":[124,1]}
_bulk批量操作
不同索引写法:
POST /_bulk{"delete":{"_index":"website","_id":124}}{"create":{"_index":"website","_id":220}}{ "title": "My first blog post" }{ "index": { "_index": "website"}}{ "title": "My second blog post" }{"update":{"_index":"website","_id":2}}{"doc":{"tittle":"sba"}}
相同索引写法:
POST /website/_bulk{"index":{}}{"name":"lisi"}{"update":{"_id":2}}{"doc":{"size":1}}
multi_match多字段执行相同match 查询:
GET /_search{"query": {"multi_match": {"query": 20,"fields": ["age","size"]}}}
range 查询指定区间:
GET /_search{"query": {"range": {"age": {"gte": 20,"lte": 24}}}}
term 查询
精确匹配:
GET /_search{"query": {"term": {"gender": "women"}}}
指定多值进行匹配:
GET /_search{"query": {"terms": {"gender": ["men","women"]}}}
exists查询
字段有值:
GET /test/_search{"query": {"exists": {"field":"tittle"}}}
字段缺值:
GET /test/_search{"query": {"bool": {"must_not": [{"exists": {"field": "tittle"}}]}}}
bool 查询
must:必须 匹配
must_not:必须不 匹配
should:满足任意语句增加 _score
如果满足这些语句中的任意语句,将增加 _score ,否则,无任何影响。它们主要用于修正每个文档的相关性得分。
filter:必须 匹配,但它以不评分、过滤模式
必须 匹配,但它以不评分、过滤模式来进行。这些语句对评分没有贡献,只是根据过滤标准来排除或包含文档。
下面的查询用于查找 field字段存在的文档。Gender字段匹配 men的文档将比其他文档拥有更高的排名GET /test/_search{"query": {"bool": {"must": [{"exists": {"field": "tittle"}}],"should": [{"match": {"gender": "men"}}]}}}GET /test/_search{"query": {"bool": {"must": [{"exists": {"field": "tittle"}}],"should": [{"exists": {"field": "tittle"}},{"range": {"birthday": {"gte": "1998-09-01"}}}]}}}用 filter 语句来重写,去掉计算得分对文档查询时间的影响GET /test/_search{"query": {"bool": {"must": [{"exists": {"field": "tittle"}}],"should": [{"exists": {"field": "tittle"}}],"filter": {"range": {"birthday": {"gte": "1998-09-01"}}}}}}
constant_score 查询:
可以使用它来取代只有 filter 语句的 bool 查询。在性能上是完全相同的,但对于提高查询简洁性和清晰度有很大帮助。GET /.test/_search{"query": {"constant_score": {"filter": {"term": {"gender": "men"}}}}}在 constant_score 查询中,它可以包含查询或过滤,为任意一个匹配的文档指定评分 1 ,忽略 TF/IDF 信息:GET /_search{"query": {"bool": {"should": [{ "constant_score": {"query": { "match": { "description": "wifi" }}}},{ "constant_score": {"query": { "match": { "description": "garden" }}}},{ "constant_score": {"query": { "match": { "description": "pool" }}}}]}}}或许不是所有的设施都同等重要——对某些用户来说有些设施更有价值。如果最重要的设施是游泳池,那我们可以为更重要的设施增加权重:GET /_search{"query": {"bool": {"should": [{ "constant_score": {"query": { "match": { "description": "wifi" }}}},{ "constant_score": {"query": { "match": { "description": "garden" }}}},{ "constant_score": {"boost": 2"query": { "match": { "description": "pool" }}}}]}}}
validate-query验证查询是否合法:
GET /.test/_validate/query{"query": {"match": {"gender": "men"}}}
explain查询不合法的原因:
GET /.test/_validate/query?explain{"query": {"match": {"gender": "men women"}}}
sort排序:
GET /_search{"query": {"match": {"gender": "men"}},"sort": [{"birthday": {"order": "desc"}}]}
sort多级排序:
GET /_search{"query": {"match": {"gender": "men women"}},"sort": [{"age": {"order": "desc"}},{"birthday": {"order": "asc"}}]}
consistency一致性:
默认规定数量即:
int( (primary + number_of_replicas) / 2 ) + 1
注:number_of_replicas 指的是在索引设置中的设定副本分片数,如当前索引拥有三个副本分片,那规定数量的计算结果即:
int( (primary + 3 replicas) / 2 ) + 1 = 3
此时你只启动两个节点,那么处于活跃状态的分片副本数量就达不到规定数量,也因此您将无法索引和删除任何文档。
consistency 参数的值可以设为 one (只要主分片状态 ok 就允许执行写操作),all(必须要主分片和所有副本分片的状态没问题才允许执行写操作), 或 quorum 。默认值为 quorum , 即大多数的分片副本状态没问题就允许执行写_操作。
size&from分页:
size 显示应该返回的结果数量,默认是 10
from 显示应该跳过的初始结果数量,默认是 0
GET /_search?size=5 查询前5条数据
GET /_search?size=5&from=5 每页显示5条数据,查询第5页
分析器
字符过滤器:
首先,字符串按顺序通过每个 字符过滤器 。他们的任务是在分词前整理字符串。一个字符过滤器可以用来去掉HTML,或者将 & 转化成 and。
分词器:
其次,字符串被 分词器 分为单个的词条。一个简单的分词器遇到空格和标点的时候,可能会将文本拆分成词条。
Token过滤器:
最后,词条按顺序通过每个 token 过滤器 。这个过程可能会改变词条(例如,小写化 Quick ),删除词条(例如, 像 a, and, the 等无用词),或者增加词条(例如,像 jump 和 leap 这种同义词)。
内置分析器
“Set the shape to semi-transparent by calling set_trans(5)”
标准分析器:
标准分析器是Elasticsearch默认使用的分析器。它是分析各种语言文本最常用的选择。它根据 Unicode联盟定义的单词边界划分文本。删除绝大部分标点。最后,将词条小写。它会产生
set, the, shape, to, semi, transparent, by, calling, set_trans, 5
简单分析器:
简单分析器在任何不是字母的地方分隔文本,将词条小写。它会产生
set, the, shape, to, semi, transparent, by, calling, set, trans
空格分析器:
空格分析器在空格的地方划分文本。它会产生
Set, the, shape, to, semi-transparent, by, calling, set_trans(5)
语言分析器:
特定语言分析器可用于 很多语言。它们可以考虑指定语言的特点。例如, 英语 分析器附带了一组英语无用词(常用单词,例如and或者the,它们对相关性没有多少影响),它们会被删除。由于理解英语语法的规则,这个分词器可以提取英语单词的词干 。
英语 分词器会产生下面的词条:
set, shape, semi, transpar, call, set_tran, 5
注意看 transparent、 calling 和 set_trans 已经变为词根格式。
type简单域类型
字符串类型:
string 5.x后不支持
text 全文检索内容,字段内容会被分析为一个个词项
keyword 结构化字段
整数类型:
浮点类型:
double,float ,half_float,scaled_float
date类型:
内部会将日期数据转换为UTC,并存储为milliseconds-since-the-epoch的long型整数。
boolean类型:
binary类型:
用base64来存储二进制形式的数据,例如图像。默认情况下,该类型的字段只存储不索引。二进制类型只支持index_name属性。
array类型:
object类型:
ip类型:
-设置字段type
PUT /.test1{"settings": {"number_of_shards": 3,"number_of_replicas": 2},"mappings": {"properties": {"tittle":{"type": "text"}}}}
index控制索引
analyzed:
not_analyzed:
索引这个域,所以它能够被搜索,但索引的是精确值。不会对它进行分析。
no:
不索引这个域。这个域不会被搜索到。
analyze查看文本分析:
GET /_analyze{"analyzer": "standard","text":"Text to analyze"}返回:{"tokens" : [{"token" : "text", //实际存储到索引中的词条"start_offset" : 0, //字符在原始字符串中的起始位置"end_offset" : 4, //字符在原始字符串中的结束位置"type" : "<ALPHANUM>","position" : 0 //词条在原始文本中出现的位置},{"token" : "to","start_offset" : 5,"end_offset" : 7,"type" : "<ALPHANUM>","position" : 1},......]}
refresh API:
刷新所有的索引:POST /_refresh只刷新my_index索引:POST /_refreshogs/_refreshrefresh_interval设置刷新频率:PUT /my_index{"settings": {"refresh_interval": "30s"}}关闭自动刷新PUT /my_index/_settings{"refresh_interval":-1}每秒自动刷新PUT /my_index/_settings{"refresh_interval":"1s"}refresh_interval 需要一个持续时间值,例如 1s(1 秒)或2m(2分钟)。一个绝对值1表示的是1毫秒 --无疑会使你的集群陷入瘫痪
flush API:
这个执行一个提交并且截断 translog 的行为在 Elasticsearch 被称作一次 flush .分片每30分钟被自动刷新(flush),或者在 translog 太大的时候也会刷新刷新my_index索引:POST /my_index/_flush刷新所有的索引并且等待所有刷新在返回前完成:POST /_flush?wait_if_ongoing
提高精度
operator :
GET /.test/_search{"query": {"match": {"msg": {"query": "pig egg","operator": "and"}}}}
minimum_should_match:
GET /.test/_search{"query": {"match": {"msg": {"query": "pig egg","minimum_should_match": "100%"}}}}GET /.test/_search{"query": {"bool": {"should": [{"match": {"msg": "pig"}},{"match": {"msg": "egg"}}],"minimum_should_match": 2}}}
boost权重:
GET /.test/_search{"query": {"bool": {"must": [{"match": {"msg": "pig"}}],"should": [{"match": {"msg":{"query": "and","boost": 2}}},{"match": {"msg": {"query": "an","boost": 3}}}]}}}
indices_boost:
GET /docs_2014_*/_search{"indices_boost": {"docs_2014_10": 3,"docs_2014_09": 2},"query": {"match": {"text": "quick brown fox"}}}这个多索引查询涵盖了所有以字符串 docs_2014_ 开始的索引。其中,索引 docs_2014_10 中的所有文件的权重是 3 ,索引 docs_2014_09 中是 2 ,其他所有匹配的索引权重为默认值 1 。
boosting 查询:
GET /_search{"query": {"boosting": {"positive": {"match": {"text": "apple"}},"negative": {"match": {"text": "pie tart fruit crumble tree"}},"negative_boost": 0.5}}}它接受 positive 和 negative 查询。只有那些匹配 positive 查询的文档罗列出来,对于那些同时还匹配 negative 查询的文档将通过文档的原始 _score 与 negative_boost 相乘的方式降级后的结果。为了达到效果, negative_boost 的值必须小于 1.0 。在这个示例中,所有包含负向词的文档评分 _score 都会减半。
dis_max查询:
{"query": {"dis_max": {"queries": [{ "match": { "title": "Brown fox" }},{ "match": { "body": "Brown fox" }}]}}}
tie_breaker:
将其他匹配语句的评分也考虑其中:{"query": {"dis_max": {"queries": [{ "match": { "title": "Quick pets" }},{ "match": { "body": "Quick pets" }}],"tie_breaker": 0.3}}}
模糊匹配:
{"multi_match": {"query": "Quick brown fox","fields": "*_title"}}
使用 ^ 字符为单个字段提升权重:
{"multi_match": {"query": "Quick brown fox","fields": [ "*_title", "chapter_title^2" ]}}
chapter_title 这个字段的 boost 值为 2 ,而其他两个字段 book_title 和 section_title 字段的默认 boost 值为 1
copy_to:
PUT /my_index{"mappings": {"properties": {"first_name":{"type": "text","copy_to": "full_name"},"last_name":{"type": "text","copy_to": "full_name"},"full_name":{"type": "text"}}}}
cross_fields 跨字段查询:
peter 和 smith 都必须同时出现在相同字段中:GET /_validate/query?explain{"query": {"multi_match": {"query": "peter smith","type": "most_fields","operator": "and","fields": [ "first_name", "last_name" ]}}}同时在 first_name 和 last_name 两个字段中查找 smith 的 IDF ,然后用两者的最小值作为两个字段的 IDFGET /_validate/query?explain{"query": {"multi_match": {"query": "peter smith","type": "cross_fields","operator": "and","fields": [ "first_name", "last_name" ]}}}
match_phrase 短语匹配:
对词语位置敏感的查询, 就可以利用位置信息去匹配包含所有查询词项,且各词项顺序也与我们搜索指定一致的文档,中间不夹杂其他词项
GET /my_index/my_type/_search{"query": {"match_phrase": {"title": "quick brown fox"}}}
slop 查询词条相隔多远时仍然能将文档视为匹配:
GET /my_index/_doc/_search{"query": {"match_phrase": {"title": {"query": "quick fox","slop": 1}}}}例:为了使查询 fox quick 匹配我们的文档, 我们需要 slop 的值为 3:Pos 1 Pos 2 Pos 3-----------------------------------------------Doc: quick brown fox-----------------------------------------------Query: fox quickSlop 1: fox|quick ↵Slop 2: quick ↳ foxSlop 3: quick ↳ fox注意:fox 和 quick 在这步中占据同样的位置。 因此将 fox quick 转换顺序成 quick fox 需要两步,或者值为 2 的 slop 。
position_increment_gap 增加当前词条 position 的指定值:
DELETE /my_index/groups/PUT /my_index/_mapping/groups{"properties": {"names": {"type": "string","position_increment_gap": 100}}}索引 names 数组时,会产生如下的结果:Position 1: johnPosition 2: abrahamPosition 103: lincolnPosition 104: smith现在我们的短语查询可能无法匹配该文档因为 abraham 和 lincoln 之间的距离为 100 。为了匹配这个文档你必须添加值为 100 的 slop 。
shingles 提高相关度评分:
匹配相邻词项GET /my_index/my_type/_search{"query": {"bool": {"must": {"match": {"title": "the hungry alligator ate sue"}},"should": {"match": {"title.shingles": "the hungry alligator ate sue"}}}}}
wildcard 通配符查询:
使用标准的 shell 通配符查询: ? 匹配任意字符, * 匹配 0 或多个字符。
GET /my_index/_search{"query": {"wildcard": {"full_name": "k?d*"}}}
regexp 正则式查询:
匹配只以 W 开始并跟随一个数字的索引:GET /my_index/_search{"query": {"regexp": {"full_name": "k[0-9].+"}}}避免使用左通配这样的模式匹配(如: *foo 或 .*foo 这样的正则式)
match_phrase_prefix 输入即搜索:
GET /my_index/_search{"query": {"match_phrase_prefix": {"full_name": {"query": "k","max_expansions": 10}}}}max_expansions 控制与前缀匹配的词的数量,它会先查找第一个与前缀 bl 匹配的词,然后依次查找搜集与之匹配的词(按字母顺序),直到没有更多可匹配的词或当数量超过 max_expansions 时结束。
index_options词频:
词频:词在文档中出现的频度是多少?频度越高,权重 越高 。 5 次提到同一词的字段比只提到 1 次的更相关。词频的计算方式如下:tf(t in d) = √frequency词 t 在文档 d 的词频( tf )是该词在文档中出现次数的平方根。如果不在意词在某个字段中出现的频次,而只在意是否出现过,则可以在字段映射中禁用词频统计:PUT /my_index{"mappings": {"doc": {"properties": {"text": {"type": "string","index_options": "docs"}}}}}将参数 index_options 设置为 docs 可以禁用词频统计及词频位置,这个映射的字段不会计算词的出现次数,对于短语或近似查询也不可用。要求精确查询的 not_analyzed 字符串字段会默认使用该设置。
idf逆向文档频率:
词在集合所有文档里出现的频率是多少?频次越高,权重 越低 。
常用词如 and 或 the 对相关度贡献很少,因为它们在多数文档中都会出现,
一些不常见词如 elastic 或 hippopotamus 可以帮助我们快速缩小范围找到感兴趣的文档。
逆向文档频率的计算公式如下:
idf(t) = 1 + log ( numDocs / (docFreq + 1))
词 t 的逆向文档频率( idf )是:索引中文档数量除以所有包含该词的文档数,然后求其对数。
norm字段长度归一值:
字段的长度是多少?字段越短,字段的权重 越高 。如果词出现在类似标题 title 这样的字段,要比它出现在内容 body 这样的字段中的相关度更高。字段长度的归一值公式如下:norm(d) = 1 / √numTerms字段长度归一值( norm )是字段中词数平方根的倒数。PUT /my_index{"mappings": {"doc": {"properties": {"text": {"type": "string","norms": { "enabled": false }}}}}}这个字段不会将字段长度归一值考虑在内,长字段和短字段会以相同长度计算评分。对于有些应用场景如日志,归一值不是很有用,要关心的只是字段是否包含特殊的错误码或者特定的浏览器唯一标识符。字段的长度对结果没有影响,禁用归一值可以节省大量内存空间。
function_score、field_value_factor相关度排序依据:
设想有个网站供用户发布博客并且可以让他们为自己喜欢的博客点赞,我们希望将更受欢迎的博客放在搜索结果列表中相对较上的位置,同时全文搜索的评分仍然作为相关度的主要排序依据,可以简单的通过存储每个博客的点赞数来实现它:PUT /blogposts/post/1{"title": "About popularity","content": "In this post we will talk about...","votes": 6}在搜索时,可以将 function_score 查询与 field_value_factor 结合使用,即将点赞数与全文相关度评分结合:GET /blogposts/post/_search{"query": {"function_score": {"query": {"multi_match": {"query": "popularity","fields": [ "title", "content" ]}},"field_value_factor": {"field": "votes"}}}}
modifier受欢迎度:
一种融入受欢迎度更好方式是用 modifier 平滑 votes 的值。换句话说,我们希望最开始的一些赞更重要,但是其重要性会随着数字的增加而降低。 0 个赞与 1 个赞的区别应该比 10 个赞与 11 个赞的区别大很多。
对于上述情况,典型的 modifier 应用是使用 log1p 参数值,公式如下:
new_score = old_score * log(1 + number_of_votes)
GET /blogposts/_search{"query": {"function_score": {"query": {"multi_match": {"query": "popularity","fields": ["title","content"]}},"field_value_factor": {"field": "votes","modifier": "log1p"}}}}
| 修饰符 | 含义 |
|---|---|
none |
不要对字段值应用任何乘数 |
log |
取字段值的常用对数 |
log1p |
将1加到字段值并取对数 |
log2p |
在字段值上加2并取公共对数 |
ln |
取字段值的自然对数 |
ln1p |
将1加到栏位值并取自然对数 |
ln2p |
将2加到字段值上并取自然对数 |
square |
对字段值求平方(乘以它本身) |
sqrt |
取字段值的平方根 |
reciprocal |
报答字段值,同1/x那里x是该字段的值 |
factor受欢迎程度:
GET /blogposts/post/_search{"query": {"function_score": {"query": {"multi_match": {"query": "popularity","fields": [ "title", "content" ]}},"field_value_factor": {"field": "votes","modifier": "log1p","factor": 2}}}}双倍效果:添加了 factor 会使公式变成这样:new_score = old_score * log(1 + factor * number_of_votes)factor 值大于 1 会提升效果, factor 值小于 1 会降低效果。
boost_mode函数:
或许将全文评分与 field_value_factor 函数值乘积的效果仍然可能太大,我们可以通过参数 boost_mode 来控制函数与查询评分 _score 合并后的结果,参数接受的值为:multiply
评分 _score 与函数值的积(默认)sum
评分 _score 与函数值的和min
评分 _score 与函数值间的较小值max
评分 _score 与函数值间的较大值replace
函数值替代评分 _score
与使用乘积的方式相比,使用评分 _score 与函数值求和的方式可以弱化最终效果,特别是使用一个较小 factor 因子时:
GET /blogposts/post/_search{"query": {"function_score": {"query": {"multi_match": {"query": "popularity","fields": [ "title", "content" ]}},"field_value_factor": {"field": "votes","modifier": "log1p","factor": 0.1},"boost_mode": "sum"}}}将函数计算结果值累加到评分 _score 。之前请求的公式现在变成下面这样:new_score = old_score + log(1 + 0.1 * number_of_votes)
max_boost限制函数的最大效果:
GET /blogposts/post/_search{"query": {"function_score": {"query": {"multi_match": {"query": "popularity","fields": [ "title", "content" ]}},"field_value_factor": {"field": "votes","modifier": "log1p","factor": 0.1},"boost_mode": "sum","max_boost": 1.5}}}无论 field_value_factor 函数的结果如何,最终结果都不会大于 1.5 ;max_boost 只对函数的结果进行限制,不会对最终评分 _score 产生直接影响。
weight过滤提成权重:
GET /_search{"query": {"function_score": {"filter": {"term": { "city": "Barcelona" }},"functions": [{"filter": { "term": { "features": "wifi" }},"weight": 1},{"filter": { "term": { "features": "garden" }},"weight": 1},{"filter": { "term": { "features": "pool" }},"weight": 2}],"score_mode": "sum",}}}
过滤 vs. 查询
首先要注意的是 filter 过滤器代替了 query 查询,在本例中,我们无须使用全文搜索,只想找到 city 字段中包含 Barcelona 的所有文档,逻辑用过滤比用查询表达更清晰。过滤器返回的所有文档的评分 _score 的值为 1 。 function_score 查询接受 query 或 filter ,如果没有特别指定,则默认使用 match_all 查询。
函数 functions
functions 关键字保持着一个将要被使用的函数列表。可以为列表里的每个函数都指定一个 filter 过滤器,在这种情况下,函数只会被应用到那些与过滤器匹配的文档,例子中,我们为与过滤器匹配的文档指定权重值 weight 为 1 (为与 pool 匹配的文档指定权重值为 2 )。
评分模式 score_mode
每个函数返回一个结果,所以需要一种将多个结果缩减到单个值的方式,然后才能将其与原始评分 _score 合并。评分模式 score_mode 参数正好扮演这样的角色,它接受以下值:multiply函数结果求积(默认)。sum函数结果求和。avg函数结果的平均值。max函数结果的最大值。min函数结果的最小值。first使用首个函数(可以有过滤器,也可能没有)的结果作为最终结果
在本例中,我们将每个过滤器匹配结果的权重 weight 求和,并将其作为最终评分结果,所以会使用 sum 评分模式。
不与任何过滤器匹配的文档会保有其原始评分, _score 值的为 1 。
配置BM25相似度算法:
PUT /my_index{"settings": {"similarity": {"my_bm25": {"type": "BM25","b": 0 //禁用字段长度规范化(field-length normalization)}}},"mappings": {"doc": {"properties": {"title": {"type": "string","similarity": "my_bm25" //自定义相似度算法},"body": {"type": "string","similarity": "BM25" //使用内置相似度算法 BM25}}}}}自定义的相似度算法可以通过关闭索引,更新索引设置,开启索引这个过程进行更新。这样可以无须重建索引又能试验不同的相似度算法配置。
terms 桶操作:
汽车经销商可能会想知道哪个颜色的汽车销量最好,用聚合可以轻易得到结果:GET /cars/_search{"size": 0, //我们并不关心搜索结果的具体内容,所以将返回记录数设置为 0 来提高查询速度。设置 size: 0 与 Elasticsearch 1.x 中使用 count 搜索类型等价。"aggs": { //聚合操作"popular_color": { //聚合指定名称"terms": { //定义单个桶的类型"field": "color.keyword"}}}}返回:{"took" : 5,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ] //因为我们设置了 size 参数,所以不会有 hits 搜索结果返回。},"aggregations" : {"popular_color" : { //作为 aggregations 字段的一部分被返回的。"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "red", //每个桶的 key 都与 color 字段里找到的唯一词对应。它总会包含 doc_count 字段,告诉我们包含该词项的文档数量。"doc_count" : 8 //每个桶的数量代表该颜色的文档数量。},{"key" : "blue","doc_count" : 4},{"key" : "green","doc_count" : 4} ] } }}
aggs聚合嵌套:
GET /cars/_search{"size": 0,"aggs": {"colors":{"terms": {"field": "color.keyword"},"aggs": {"avg_price":{"avg": {"field": "price"}},"make":{"terms": {"field": "make.keyword"},"aggs": {"min_price":{"min": {"field": "price"}},"max_price":{"max": {"field": "price"} } } } } } }}返回结果:{"took" : 36,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"colors" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "red","doc_count" : 8,"avg_price" : {"value" : 32500.0},"make" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "honda","doc_count" : 6,"max_price" : {"value" : 20000.0},"min_price" : {"value" : 10000.0}},{"key" : "bmw","doc_count" : 2,"max_price" : {"value" : 80000.0},"min_price" : {"value" : 80000.0}}]}},{"key" : "blue","doc_count" : 4,"avg_price" : {"value" : 20000.0},"make" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "ford","doc_count" : 2,"max_price" : {"value" : 25000.0},"min_price" : {"value" : 25000.0}},{"key" : "toyota","doc_count" : 2,"max_price" : {"value" : 15000.0},"min_price" : {"value" : 15000.0}}]}},{"key" : "green","doc_count" : 4,"avg_price" : {"value" : 21000.0},"make" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "ford","doc_count" : 2,"max_price" : {"value" : 30000.0},"min_price" : {"value" : 30000.0}},{"key" : "toyota","doc_count" : 2,"max_price" : {"value" : 12000.0},"min_price" : {"value" : 12000.0} } ] } } ] } }}
条形图统计:
GET /cars/_search{"size": 0,"aggs": {"price":{"histogram": { //价格区间,每个区间2万"field": "price","interval": 20000},"aggs": {"revenue":{"sum": { //区间价格合计"field": "price"} } } } }}返回结果:{"took" : 3,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"price" : {"buckets" : [{"key" : 0.0, //区间1"doc_count" : 6, //数据条数"revenue" : {"value" : 74000.0 //sum总和}},{"key" : 20000.0,"doc_count" : 8,"revenue" : {"value" : 190000.0}}......}
extended_stats计算:
GET /cars/_search{"size": 0,"aggs": {"make":{"terms": {"field": "make.keyword","size": 10},"aggs": {"stats":{"extended_stats": {"field": "price"} } } } }}返回结果:{"took" : 31,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"make" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "honda","doc_count" : 6,"stats" : {"count" : 6,"min" : 10000.0,"max" : 20000.0,"avg" : 16666.666666666668, //平均值"sum" : 100000.0,"sum_of_squares" : 1.8E9, //平方和"variance" : 2.222222222222221E7, //方差"std_deviation" : 4714.045207910315, //标准偏差"std_deviation_bounds" : { //标准偏差界限"upper" : 26094.757082487296,"lower" : 7238.5762508460375}}}......}
date_histogram时间统计:
GET /cars/_search{"size": 0,"aggs": {"sales":{"date_histogram": {"field": "sold", //查询日期字段"calendar_interval":"month", //按月buckets"format": "yyyy-MM-dd" //格式化}}}}返回结果:{"took" : 3,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"sales" : {"buckets" : [{"key_as_string" : "2014-01-01","key" : 1388534400000,"doc_count" : 2},{"key_as_string" : "2014-02-01","key" : 1391212800000,"doc_count" : 2}......}
返回空buckets:
GET /cars/_search{"size": 0,"aggs": {"sales":{"date_histogram": {"field": "sold","calendar_interval":"month","format": "yyyy-MM-dd","min_doc_count": 0, //强制返回空 buckets"extended_bounds": { //强制返回区间内日期"min": "2014-01-01","max": "2014-12-31"}}}}}返回结果:{"took" : 7,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"sales" : {"buckets" : [{"key_as_string" : "2014-01-01","key" : 1388534400000,"doc_count" : 2},{"key_as_string" : "2014-02-01","key" : 1391212800000,"doc_count" : 2}......}
post_filter 过滤搜索结果:
GET /cars/_search{"size": 0,"query": {"match": {"make": "ford"}},"post_filter": {"term": {"color": "green"}},"aggs": {"all_colors":{"terms": {"field": "color.keyword"}}}}
排序:
在聚合中引入order对象, 它允许我们可以根据以下几个值中的一个值进行排序:
_count
按文档数排序。对 terms 、 histogram 、 date_histogram 有效。
_term
_key
按每个桶的键值数值排序(理论上与 _term 类似)。 只在 histogram 和 date_histogram 内使用。
GET /cars/_search{"size": 0,"aggs": {"colors":{"terms": {"field": "color.keyword","order": {"_count": "desc"}}}}}
自定义排序
GET /cars/_search{"size": 0,"aggs": {"colors":{"terms": {"field": "color.keyword","order": {"avg_price":"desc" //自定义avg_price排序}},"aggs": {"avg_price":{ //实现avg_price排序逻辑"avg": {"field": "price"}}}}}}GET /cars/_search{"size": 0,"aggs": {"colors":{"terms": {"field": "color.keyword","order": {"status.max":"desc" //使用 . 符号,根据感兴趣的度量进行排序}},"aggs": {"status":{"extended_stats": {"field": "price" //根据status的价格降序排序}}}}}}返回结果:{"took" : 7,"timed_out" : false,"_shards" : {"total" : 1,"successful" : 1,"skipped" : 0,"failed" : 0},"hits" : {"total" : {"value" : 16,"relation" : "eq"},"max_score" : null,"hits" : [ ]},"aggregations" : {"colors" : {"doc_count_error_upper_bound" : 0,"sum_other_doc_count" : 0,"buckets" : [{"key" : "red","doc_count" : 8,"status" : {"count" : 8,"min" : 10000.0,"max" : 80000.0,"avg" : 32500.0,"sum" : 260000.0,"sum_of_squares" : 1.46E10,"variance" : 7.6875E8,"std_deviation" : 27726.341266023544,"std_deviation_bounds" : {"upper" : 87952.6825320471,"lower" : -22952.68253204709}}},{"key" : "green","doc_count" : 4,"status" : {"count" : 4,"min" : 12000.0,"max" : 30000.0,"avg" : 21000.0,"sum" : 84000.0,"sum_of_squares" : 2.088E9,"variance" : 8.1E7,"std_deviation" : 9000.0,"std_deviation_bounds" : {"upper" : 39000.0,"lower" : 3000.0}}}......}
cardinality去重:
GET /cars/_search{"size": 0,"aggs": {"distinct_colors": {"cardinality": {"field":"color.keyword"}}}}返回结果:{......"aggregations" : {"distinct_colors" : {"value" : 3}}}
