es_tips
00 query和filter
全文检索及任何使用相关性评分的场景,使用query检索
除此之外的其他使用filter过滤器过滤
查询query和过滤器filter已经合并(在1.x版本是分开的)
高版本的es中,任何查询字句,都可以在查询上下文query中用作查询,或者在过滤器上下文中用作过滤器。
GET /_search
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Search" }},
{ "match": { "content": "Elasticsearch" }}
],
"filter": [
{ "term": { "status": "published" }},
{ "range": { "publish_date": { "gte": "2015-01-01" }}}
]
}
}
}
Query:除了判断该文档是否匹配之外,还会计算一个_score来判断文档的匹配度,表示这个文档匹配这个查询子句的程度如何
Filter:只是简单判断文档是否匹配,答案只有匹配或者不匹配,主要用于过滤结构化数据。
01 template和ingest
可用通过template脚本创建mapping
ingest数据预处理,在写入前进行数据预处理,字段拆解、截取、更换字段名等
02 es相关文档
03 Mac本地docker安装cerebro之后,连不上docker创建的es集群
cerebro链接es集群时,需要使用docker里的网络地址,而不是映射的本机网络地址
是http://172.28.0.2:9200这种的,而不是http://127.0.0.1:9200
04 scripting
脚本用途:
创建运行时字段
搜索API的script_fields参数,脚本字段
script_socre可以用来影响文档score,也可以用脚本
对文档进行更新、删除、跳过修改,支持传递部分文档将其合并到现有文档中
- 更新文档内容
PUT my-index-000001/_doc/1
{
"counter": 1,
"tags": ["red"]
}
POST my-index-000001/_update/1
{
"script": {
"source": "ctx._source.counter += params.count",
"lang": "painless",
"params": {
"count": 4
}
}
}
# 给counter字段+4
"_source" : {
"counter" : 5,
"tags" : [
"red"
]
}
POST my-index-000001/_update/1
{
"script": {
"source": "ctx._source.tags.add(params['tag'])",
"lang": "painless",
"params": {
"tag": "blue"
}
}
}
# tags增加blue
"_source" : {
"counter" : 5,
"tags" : [
"red",
"blue"
]
}
POST my-index-000001/_update/1
{
"script": {
"source": "if(ctx._source.tags.contains(params['tag'])) {ctx._source.tags.remove(ctx._source.tags.indexOf(params['tag']))}",
"lang": "painless",
"params": {
"tag": "blue"
}
}
}
# 如果blue存在,则删除blue
- 增加或者减少文档字段
POST my-index-000001/_update/1
{
"script": "ctx._source.new_field = 'value_of_new'"
}
POST my-index-000001/_update/1
{
"script": "ctx._source.remove('new_field')"
}
- 更改脚本操作(tags包含green,就删除doc,否则什么都不做)
POST my-index-000001/_update/1
{
"script": {
"source": " if(ctx._source.tags.contains(params['tag'])) {ctx.op = 'delete'} else {ctx.op = 'none'} ",
"lang": "painless",
"params": {
"tag":"green"
}
}
}
脚本可以通过stored script APIs进行存储、查询、删除
在大的索引上,尽量不使用脚本参与查询过程或排序,这样会让搜索比较慢,合适的方法是通过预先构建好相应的字段,直接使用构建的字段进行查询或拍讯
脚本常用的场景
字段提取,从一个大的非结构化字段中,提取需要的部分数据,可以使用基于正则的Grok,或者简单的Dissect通过分隔符来作匹配。
在mapping中定义运 行时字段,然后就可以把运行时字段当做普通字段一样作查询了
也可以在_search中,使用runtime_mappings定义一个运行时字段,临时使用一下
根据使用位置,脚本可以访问文档字段和一些特殊变量
当script使用在update/update-by-query/reindex APIs的时候,可以访问ctx变量,ctx暴露如下内容:
-
ctx._source 进入文档的_source字段
-
ctx.op 可以应用于文档的操作,index/delete
-
ctx._index 进入文档的元数据字段,某些可能是只读的
05 es中如何测试分词器
Testing analyzers | Elasticsearch Guide [6.6] | Elastic
全局
POST /_analyze
{
"tokenizer":"ik_smart",
"text":"中华人民共和国国歌"
}
某个索引(自定义分词器也可)
GET my_index/_analyze
{
"analyzer":"your analyzer",
"text":"中华人民共和国国歌"
}