Last active
March 12, 2024 22:25
-
-
Save awjian/e71c4910a1f5ae53af87b38d758c0a52 to your computer and use it in GitHub Desktop.
sort and facet in Atlas Search with child fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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