python elasticsearch update by query

  1. 创建索引以及添加数据
PUT test
{
  "mappings": {
    "properties": {
      "test":{
        "type": "nested"
    }
  }
}}


GET test/_mapping


PUT test/_doc/1
{
  "test":{"name":"ellis","age":100}
}

  1. elasticsearch包
from elasticsearch import Elasticsearch
conn = Elasticsearch(hosts=['192.168.214.133'],port=31200,http_auth="elastic:ellischen")

update_by_query = {
  "query": {
    "nested": {
      "path": "test",
      "query": {
        "term": {
          "test.name": {
            "value": "ellis"
          }
        }
      }
    }
  },
  "script": {
    "source": "ctx._source['test']['age']+=1",
    "params": {"age":101}, 
    "lang": "painless"
  }
}


conn.update_by_query(index='test',body=update_by_query)
  1. elasticsearch-dsl包
from elasticsearch_dsl import connections
from elasticsearch_dsl import Search
from elasticsearch_dsl import Q as esQ
from elasticsearch_dsl import UpdateByQuery
conn = connections.create_connection(hosts=['192.168.214.133'],port=31200,http_auth="elastic:ellischen")
source = "ctx._source['test']['age']=params.age"
params = {"age":110}
query_body=esQ('nested',**{"path":'test',"query":esQ('term',**{"test.name":{"value":"ellis"}})})
update_by_query = UpdateByQuery().using(conn).index('test').query(query_body).script(source=source,params=params)

update_by_query.execute()
  1. from_dict 方法
from elasticsearch_dsl import connections
from elasticsearch_dsl import Search
from elasticsearch_dsl import Q as esQ
from elasticsearch_dsl import UpdateByQuery
conn = connections.create_connection(hosts=['192.168.214.133'],port=31200,http_auth="elastic:ellischen")
# source = "ctx._source['test']['age']=params.age"
# params = {"age":110}
# query_body=esQ('nested',**{"path":'test',"query":esQ('term',**{"test.name":{"value":"ellis"}})})
# update_by_query = UpdateByQuery().using(conn).index('test').query(query_body).script(source=source,params=params)

# update_by_query.execute()

update_by_query = {
  "query": {
    "nested": {
      "path": "test",
      "query": {
        "term": {
          "test.name": {
            "value": "ellis"
          }
        }
      }
    }
  },
  "script": {
    "source": "ctx._source['test']['age']+=1",
    "params": {"age":101}, 
    "lang": "painless"
  }
}
search = UpdateByQuery().from_dict(update_by_query).using(conn).index('test')
search.execute()

你可能感兴趣的:(elasticsearch,Python,python,elasticsearch)