elasticsearch使用painless脚本进行自定义算分

###查看es版本
GET  http://172.16.101.102:9200?pretty


### 查看索引mapping
get http://172.16.101.102:9200/godproduct/product/_mapping?pretty 
Content-Type: application/application/json

### 查看写入分词情况
GET http://172.16.101.102:9200/godproduct/_analyze?pretty&analyzer=ik_max_word&text=雅诗兰黛眼霜

### 搜索分词情况
GET http://172.16.101.102:9200/godproduct/_analyze?pretty&analyzer=ik_smart&text=雅诗兰黛眼霜

###添加mapping字段
PUT http://172.16.101.102:9200/godproduct/product/_mapping
Content-Type: application/json

{
    "properties": {
        "tempfield01": {
            "type": "keyword"
        },
         "tempfield02": {
            "type": "integer"
        }
    }
}

### 修改字段 update_by_query
POST http://172.16.101.102:9200/godproduct/product/_update_by_query
Content-Type: application/json

{
     "query":{
        "term":{
            "pid":"p3274226"
        } 
    },
    "script":{
        "inline":"ctx._source.tempfield01=params.tempfield01;ctx._source.tempfield02=params.tempfield02",
        "params":{ "tempfield01":"update_by_query_test02",
            "tempfield02":1010  },
        "lang":"painless"
    }
}

### update 通过_updateAPI的script,我们可以增加一个新的field:nick
POST http://172.16.101.102:9200/godproduct/product/208330615/_update
Content-Type: application/json

{
    "script":{
        "inline":"ctx._source.nickname=params.tempfield01;ctx._source.tempfield01=params.tempfield01",
        "params":{ "tempfield01":"update_by_query_test04",
            "tempfield02":1011  },
        "lang":"painless"
    }
}

### update keyword字段为数组,必须一次性保存成数组,否则就变成了字符串
POST http://172.16.101.102:9200/godproduct/product/208330615/_update
Content-Type: application/json

{
    "script":{
        "inline":"ctx._source.promotions=params.proms",
        "params":{ "proms":["10003:2","1000:1"]},
                 
        "lang":"painless"
    }
}


### 追加数组
POST http://172.16.101.102:9200/godproduct/product/208330615/_update
Content-Type: application/json

{
    "script":{
        "inline":"ctx._source.promotions.add(params.proms)",
        "params":{ "proms":"10002:3"},
                 
        "lang":"painless"
    }
}

### get document by docid
GET http://172.16.101.102:9200/godproduct/product/208330615/?pretty

### match搜索
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
    "query": {
        "match": {
            "title": {
                "query": "专题"
            }
        }
    }
}

### term 查询
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
    "query": {
        "term": {
            "pid":  "p3274226"           
        }
    }
}

### match_phrase查询 会对输入做分词,但是需要结果中也包含所有的分词,而且顺序要求一样
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
    "query": {
        "match_phrase": {
            "title":  "樱花微精华露200ml"           
        }
    }
}

### query_string查询 和match类似,但是match需要指定字段名,query_string是在所有字段中搜索,范围更广泛
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
    "query": {
        "query_string": {
            "query":  "雅诗兰黛"           
        }
    }
}

### 复杂bool query,采用了“匹配越多越好”的方法,因此来自每个匹配的must或should子句的分数将添加在一起,以提供每个文档的最终_score。
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
  "query": {
    "bool" : {
      "must" : {
        "match" : { "title" : "雅诗兰黛眼霜" }
      },
      "filter": {
        "term" : { "bid" : 10123 }
      },
      "must":{
          "range":{
            "stock":{ "gte" : 1, "lte" : 500} 
          }
      },
       "must_not" : {
        "term" : {   "isshow" : false  }
      },
      "should" : [{
        "nested": {
        "path": "catalogs",
        "query": 
            {"term": {"catalogs.sku" :  "1910040"}}       
        }
    },
        {"term":{"issellout": false}}
    ],
     "minimum_should_match" : 1,
      "boost" : 1.0
    } 
  }
}


###  function score ,自定义算分
### modifiers有:none(默认值),log,log1p,log2p,ln,ln1p,ln2p,square,sqrt以及reciprocal
POST  http://172.16.101.102:9200/godproduct/product/_search?pretty
Content-Type: application/json

{
	"query": {
		"function_score": {
			"query": {
				"match": {
					"title": {
						"query": "雅诗兰黛眼霜"
					}
				}
			},
			"functions": [				
                {
		            "weight":20  ,
		            "filter": { "term": { "fcateid":1086 }}   
	            },
                {
		            "weight":20  ,
		            "filter": { "term": { "fcateid":1087 }}   
	            },                {
		            "weight":30  ,
		            "filter": { "term": { "bid":10123 }}   
	            },                {
                    "weight":100  ,
                     "filter":{"wildcard": { "orTitle":"*樱花微精华露*"} }
                },                {
                 "field_value_factor": {
                        "field": "rankscore",
                        "modifier": "log1p",
                        "factor": 5,
                        "missing":0
                    }
                },                  {
                 "field_value_factor": {
                        "field": "stock",
                        "modifier": "log1p",
                        "factor": 0.001,
                        "missing":0
                    }
                },                {
					"script_score": {
						"script":
                        {   "line": "def sellOut=doc['issellout'].value; def showSellOut=doc['showsellout'].value; if(sellOut&&showSellOut) return params.showSelloutBoost; else if(sellOut) return -params.selloutBoost; else return 0;",
                            "params":{
                                "showSelloutBoost":-50,
                                "selloutBoost":-500000
                            }               
                        }
                    }
				},                {
					"script_score": {
						"script": "int maxSize=1000; int groupId=1000; def groupInId=(long)doc['sgid'].value; def sortnum=(long)doc['gsortnum'].value; if(groupId <= 0) return 0; if(groupInId != groupId) return 0;  return 6.0* (maxSize - 20 * sortnum);"
					}
				},                 {
					"script_score": {
						"script": "def topic='844:'; def list=doc['topics']; if(list == null || list.size()==0) return 0; for(def item :list){if(item.startsWith(topic)){ int index=item.indexOf(':'); if(index>0) return Integer.parseInt(item.substring(index+1))*1;}} return 0; "                       
					}
				},                {
					"script_score": {
						"script":{ 
                            "inline":"def promId=params.promId; if(promId==null) return 0; def list=doc['promotions']; if(list == null || list.size()==0) return 0; for(def id :list){if(id.startsWith(promId)){ int index=id.indexOf(':'); if(index>0) return 6*(params.maxSize-Integer.parseInt(id.substring(index+1))*params.boost);}} return 0; ",                      
                            "params":{
                                    "boost":20,
                                    "promId":"10003",
                                    "maxSize":10000
                                }
                        }
                    }
				}


            ],
			"score_mode": "sum",
			"boost_mode": "replace",
			"max_boost": 1000
        }    
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,可以使用Elasticsearch提供的Script来编写自定义排序的脚本。以下是一个示例Java脚本,实现按照_score和age字段进行加权排序: ```java import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.sort.ScriptSortBuilder; import org.elasticsearch.search.sort.SortOrder; Script script = new Script( ScriptType.INLINE, "painless", "_score * 0.7 + doc['age'].value * 0.3", null); ScriptSortBuilder scriptSortBuilder = new ScriptSortBuilder(script, ScriptSortBuilder.ScriptSortType.NUMBER); scriptSortBuilder.order(SortOrder.DESC); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); searchSourceBuilder.sort(scriptSortBuilder); SearchRequest searchRequest = new SearchRequest("my_index"); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); ``` 在上面的示例中,我们使用Painless脚本语言来编写自定义排序的脚本,将_score和age字段进行了加权排序。并且通过ScriptSortBuilder将脚本排序应用到搜索请求中,并执行搜索请求,最后将结果存储在searchResponse中。 需要注意的是,在使用脚本排序时,需要在Elasticsearch中启用脚本评分功能,可以通过设置"script.max_compilations_per_minute"参数来实现。此外,如果要使用其他脚本语言,可以修改ScriptType和脚本内容来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值