【弄nèng - Elasticsearch】DSL入门篇(十一)—— Script 脚本查询

脚本查询,语法跟版本有关,我是用的es是5.2.2

1. Script Query 比较大小过滤

POST  schools/classes/_search
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "inline": "doc['price'].value > 7",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

过滤价格大于7的文档

效果

{
  "took": 18,
  "timed_out": false,
  "_shards": {
    "total": 3,
    "successful": 3,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "schools",
        "_type": "classes",
        "_id": "5",
        "_score": 1,
        "_source": {
          "classes_id": 5,
          "name": "班级5",
          "address": "7-深圳市福田区福华路1",
          "price": 7.4,
          "timestamp": 1572573660000
        }
      },
      {
        "_index": "schools",
        "_type": "classes",
        "_id": "11",
        "_score": 1,
        "_source": {
          "classes_id": 11,
          "name": "班级11",
          "address": "深圳市福田区福华路11",
          "price": 11.4,
          "timestamp": 1572573660000,
          "users": [
            {
              "name": "SIMA",
              "age": "11",
              "price": 13.4
            },
            {
              "name": "LIYAO",
              "age": "13",
              "price": 13.2
            }
          ]
        }
      }
    ]
  }
}

使用参数

POST  schools/classes/_search
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "inline" : "doc['price'].value > params.param1",
                        "lang"   : "painless",
                        "params" : {
                            "param1" : 7
                        }
                    }
                }
            }
        }
    }
}

效果跟上面一样

2. Script Query 数据处理

查询数据,简单处理后返回,如下地址+ “hello”

POST  schools/classes/_search
{
  "query":{
    "match_all": {}
  }, 
  "script_fields": {
    "test1": {
      "script": "doc['address'].value +'hello'"
    }
  }
}

效果

[
      {
        "_index": "schools",
        "_type": "classes",
        "_id": "4",
        "_score": 1,
        "fields": {
          "test1": [
            "6-深圳市福田区福华路1hello"
          ]
        }
      },
      {
        "_index": "schools",
        "_type": "classes",
        "_id": "5",
        "_score": 1,
        "fields": {
          "test1": [
            "7-深圳市福田区福华路1hello"
          ]
        }
      }
]

项目推荐

IT-CLOUD :IT服务管理平台,集成基础服务,中间件服务,监控告警服务等。
IT-CLOUD-ACTIVITI6 :Activiti教程源码。博文在本CSDN Activiti系列中。
IT-CLOUD-ELASTICSEARCH :elasticsearch教程源码。博文在本CSDN elasticsearch系列中。

开源项目,持续更新中,喜欢请 Star~

发布了160 篇原创文章 · 获赞 46 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/yy756127197/article/details/103404036