Skip to content

Instantly share code, notes, and snippets.

@clintongormley
Created May 18, 2013 10:50
Show Gist options
  • Save clintongormley/5604037 to your computer and use it in GitHub Desktop.
Save clintongormley/5604037 to your computer and use it in GitHub Desktop.
Scoring missing nested docs
# delete index if exists
curl -XDELETE localhost:9200/test/
# create index with default settings
curl -XPOST localhost:9200/test/
# create mapping
curl -XPUT localhost:9200/test/product/_mapping -d '
{
"product" : {
"properties" : {
"price" : {
"type" : "float"
},
"product" : {
"type" : "string"
},
"review" : {
"type": "nested",
"include_in_parent": true,
"properties" : {
"rate" : {
"type" : "integer"
},
"user" : {
"properties" : {
"member_id" : {
"type" : "long"
},
"name" : {
"type" : "string"
}
}
}
}
}
}
}
}
'
# add some data
curl -XPUT localhost:9200/test/product/1 -d '
{
"product": "product 1",
"price": 40,
"review": [
{
"user": {
"name": "user1",
"member_id": "23242"
},
"rate": 5
},
{
"user": {
"name": "user2",
"member_id": "63332"
},
"rate": 4
},
{
"user": {
"name": "anonymous"
},
"rate": 1
}
]
}
'
curl -XPUT localhost:9200/test/product/2 -d '
{
"product": "product 2",
"price": 50,
"review": [
{
"user": {
"name": "anonymous"
},
"rate": 1
}
]
}
'
curl -XPUT localhost:9200/test/product/3 -d '
{
"product": "product 3",
"price": 44.99,
"review": []
}
'
curl -XPUT localhost:9200/test/product/4 -d '
{
"product": "product 4",
"price": 47.99
}
'
curl -XGET 'http://127.0.0.1:9200/test/product/_search?pretty=1' -d '
{
"query" : {
"bool" : {
"disable_coord" : 1,
"should" : [
{
"custom_score" : {
"script" : "3",
"query" : {
"constant_score" : {
"filter" : {
"missing" : {
"field" : "review.user.member_id"
}
}
}
}
}
},
{
"filtered" : {
"filter" : {
"exists" : {
"field" : "review.user.member_id"
}
},
"query" : {
"nested" : {
"query" : {
"custom_score" : {
"script" : "doc[\u0027review.user.member_id\u0027].empty ? 3 : doc[\u0027review.rate\u0027].value",
"query" : {
"match_all" : {}
}
}
},
"score_mode" : "avg",
"path" : "review"
}
}
}
}
]
}
}
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment