You need to use the Source filtering for getting the _source
back with only the requested fields.
Just replace the fields
in your query with _source
as:
body: {
size: 100,
from: 0,
query: { match_all: {} },
_source: ["object"] <--- this is an object
}
Here's why the results (hit counts) are different when you used the fields option:
The fields
parameter is about fields that are explicitly marked as stored in the mapping, which is off by default and generally not recommended.
For backwards compatibility, if the fields
parameter specifies fields which are not stored (store
mapping set to false), it will load the _source
and extract it from it.
Also only leaf fields can be returned via the field option. So object fields can’t be returned and such requests will fail.
But if you search across multiple indices with an object
field in the fields
option and if this field is not present or mapped to a different datatype other than object
(like string
or long
) in all or some of the indices, then such requests won't fail and will be returned in the hits array.
This is the reason why you get different values for hits.total
and hits.hits.length
Output of a typical such query would look like:
{
"took": 91,
"timed_out": false,
"_shards": {
"total": 10,
"successful": 9,
"failed": 1,
"failures": [
{
"shard": 1,
"index": "test_index1",
"node": "GQN77mbqTSmmmwQlmjSBEg",
"reason": {
"type": "illegal_argument_exception",
"reason": "field [object] isn't a leaf field"
}
}
]
},
"hits": {
"total": 25,
"max_score": 1,
"hits": [
{
"_index": "test_index2",
"_type": "test_type1",
"_id": "1",
"_score": 1
},
{
"_index": "test_index2",
"_type": "test_type2",
"_id": "1",
"_score": 1
},
{
"_index": "test_index2",
"_type": "test_type3",
"_id": "1",
"_score": 1,
"fields": {
"object": [
"simple text" <-- here the field 'object' is a leaf field
]
}
}
]
}
}
Here hits.total
is the total no: of docs across all indices searched as it is a match all query.
And hits.hits.length
is the no: of docs for which the request did not fail.