I think you misunderstood the use cases of the search indexing. Actually of any indexing. Indexes are used for the preliminary elimination of unmatched documents. When we use an index for the first time, the resulting set of documents no longer are part of the index. that is also why we try to put any query that can use indexes at the top.
Processing indexes is fast and in case the result of this first stage satisfies your needs in 1 step then you can use the result as is. otherwise, you have to go through the remaining procedure of finding what you need. Unfortunately, the remaining part is nasty without indexes but not hopeless, because the ugly part lies only in the time required to complete operations.
The following aggregation pipeline does something similar to what you too should do. search by using the search index at the first stage, then unwind the profiles array, then search again with $match (nasty part, you need to use it on fields manually), then do whatever else you need to do in the remaining stages. I chose to flatten the result by replacing the root element. you can select fields and continue only with them
[
{
"$search": {
"index": "profiles_names",
"text": {
"query": "typea",
"path": {
"wildcard": "*"
}
}
}
},
{
"$unwind": {
"path": "$profiles",
"preserveNullAndEmptyArrays": false
}
},
{
"$match": {
"profiles.type": "typea"
}
},
{
"$replaceRoot": {
"newRoot": "$profiles"
}
}
]
The above query does not need, but here are the data I used and the search index:
Click here to see the Data I used
[
{
"username": "usera",
"profiles": [
{ "type": "typea", "pageName": "abc" },
{ "type": "typeb", "pageName": "cde" }
]
},
{
"username": "userb",
"profiles": [
{ "type": "typea", "pageName": "asd" },
{ "type": "typec", "pageName": "zxc" }
]
},
{
"username": "userc",
"profiles": [
{ "type": "typeb", "pageName": "jkl" },
{ "type": "typec", "pageName": "bnm" }
]
}
]
Click here to see Search Index I used
{
"mappings": {
"dynamic": false,
"fields": {
"profiles": {
"fields": {
"pageName": {
"analyzer": "diacriticFolder",
"searchAnalyzer": "diacriticFolder",
"type": "string"
},
"type": {
"analyzer": "diacriticFolder",
"searchAnalyzer": "diacriticFolder",
"type": "string"
}
},
"type": "document"
}
}
},
"analyzers": [
{
"charFilters": [],
"name": "diacriticFolder",
"tokenFilters": [
{
"type": "icuFolding"
}
],
"tokenizer": {
"type": "keyword"
}
}
]
}