Reputation: 73
I am having an index with the following mapping (ignore other fields). The "user_data" field is a nested array of objects. Now, I would like to query the ES result by using a "name" string as text query. My search purpose is if the search results' "user_data" array contains an item with the same "name" string, then these results should be displayed first, and the order of these search results should be descending in terms of "counts" of the same "name" item. Does anyone know how to write the ES query conditions? Thanks much in advance.
Mapping snippet:
{
"index_1": {
"mappings": {
"properties": {
"user_data": {
"type": "nested",
"properties": {
"counts": {
"type": "integer"
},
"name": {
"type": "text"
}
}
}
}
}
}
}
Example data in the array of "user_data" in a certain doc:
"user_data": [{
"counts": "5",
"name": "abcd"
},
{
"counts": "1",
"name": "test 001"
}
]
So for example, if I query ES results with string "abcd", and there are 3 results for "abcd", two docs have item with "name" = "abcd", then these two docs should be displayed first, and then if one doc's "abcd" item has counts=5, the other doc's "abcd" item has counts=8, then the latter one should be displayed as the very first result, and the former one should be displayed as the 2nd result.
Does anyone know how to write the query conditions for this requirement? Thanks much in advance.
Upvotes: 0
Views: 654
Reputation: 3271
I did a example and I did the query with sort by field counts.
PUT idx_test
{
"mappings": {
"properties": {
"user_data": {
"type": "nested",
"properties": {
"counts": {
"type": "integer"
},
"name": {
"type": "text"
}
}
}
}
}
}
Documents
POST idx_test/_doc
{
"user_data": [
{
"counts": "5",
"name": "abcd"
},
{
"counts": "1",
"name": "test 001"
}
]
}
POST idx_test/_doc
{
"user_data": [
{
"counts": "8",
"name": "abcd"
},
{
"counts": "1",
"name": "test 001"
}
]
}
POST idx_test/_doc
{
"user_data": [
{
"name": "abcd"
}
]
}
Query
POST idx_test/_search
{
"query": {
"nested": {
"path": "user_data",
"query": {
"match": {
"user_data.name": "abcd"
}
}
}
},
"sort": [
{
"user_data.counts": {
"order": "asc",
"nested_path": "user_data"
}
}
]
}
Upvotes: 2