Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save awjian/e71c4910a1f5ae53af87b38d758c0a52 to your computer and use it in GitHub Desktop.

Select an option

Save awjian/e71c4910a1f5ae53af87b38d758c0a52 to your computer and use it in GitHub Desktop.
sort and facet in Atlas Search with child fields
// Index for faceting and sorting on child fields
{
"mappings": {
"dynamic": true,
"fields": {
"embeddedDocField": [
{
"type": "document",
"dynamic": true,
"fields": {
"facetField": {
"type": "stringFacet"
},
"sortField": {
"type": "token"
}
}
},
{
"type": "embeddedDocuments",
"dynamic": true,
"fields": {
"sortField": [
{
"type": "string"
},
{
"type": "autocomplete"
}
]
}
}
]
}
}
}
# CASE 1: Facet query, grouped by parent docs
[
{
$searchMeta: {
facet: {
facets: {
childFieldFacet: {
path: "embeddedDocField.facetField",
type: "string"
}
}
}
}
}
]
# CASE 2: Sort query; parent docs sorted within Atlas search; child docs sorted with $sortArray
[
{
$search: {
text: {
path: "embeddedDocField.textField",
query: "query"
}
// sorts parent docs
sort: {
"embeddedDocField.sortField": -1
}
}
},
{
$project: {
"_id": 1,
"embeddedDocField": 1,
//sorts child docs
"sortedChildDocs": {
$sortArray: {
input: "$embeddedDocField",
sortBy: { "sortField": -1 }
}
}
}
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment