Skip to content

Instantly share code, notes, and snippets.

@redserpent7
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redserpent7/e1d52afff435f3d759e1 to your computer and use it in GitHub Desktop.
Save redserpent7/e1d52afff435f3d759e1 to your computer and use it in GitHub Desktop.
ES example of groovy not throwing any exceptions when ctx._source is misspelled.
export ES_HOST=http://localhost:9200
# Create an index we will call it users
curl -XPUT $ES_HOST/users
# Configure mapping, files with path and size
curl -XPUT $ES_HOST/users/files/_mapping -d '
{
"doc": {
"properties": {
"path": {"type": "string"},
"size": {"type": "long"}
}
}
}'
# index some files/documents
curl -X PUT $ES_HOST/users/files/1 -d '
{
"path" : "usr/files/somefile.txt",
"size" : 500
}'
curl -X PUT $ES_HOST/users/files/2 -d '
{
"path" : "usr/files/somefile2.txt",
"size" : 700
}'
# Now using the search by query plugin, try renaming the file with a script
curl -XPOST $ES_HOST/users/files/_update_by_query -d '
{
"query": {
"bool": {
"must": [
{
"term": {
"path": "usr/files"
}
}]
}
},
"script": "def str = ctx_source.path;\ndef str2 = str.replaceAll(\"usr/files\", \"usr/files2\");\nctx._source.path = str2;"
}'
# The result will look like this
# {
# "ok":true,
# "took":14,
# "total":2,
# "updated":0,
# "indices":[
# {
# "new_index":{}
# }]
# }
# As it indicate that the query was able to match the two docs yet they did not get updated
# Nothing in the log indicates as to why it failed to update
# If you have a sharp eye you will notice that in the _update_by_query script we are missing a '.'
# def str = ctx_source should be ctx._source
# yet groovy never complains about ctx_source not being in scope
# Updating the script will get the job done
curl -XPOST $ES_HOST/users/files/_update_by_query -d '
{
"query": {
"bool": {
"must": [
{
"term": {
"path": "usr/files"
}
}]
}
},
"script": "def str = ctx._source.path;\ndef str2 = str.replaceAll(\"usr/files\", \"usr/files2\");\nctx._source.path = str2;"
}'
# And now all documents have been updates successfully
# {
# "ok":true,
# "took":12,
# "total":2,
# "updated":2,
# "indices":[
# {
# "new_index":{}
# }]
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment