Sorting
Learn how to sort the search results in ZBSearch.
To sort, ZBSearch uses the properties defined in the schema to know on which properties you want to sort.
const db = create({
schema: {
title: "string",
year: "number",
inPromotion: "boolean",
meta: {
tag: "string",
rating: "number",
favorite: "boolean",
},
},
});
const results = search(db, {
term: "prestige",
sortBy: {
property: "title", // or 'year', 'inPromotion'
},
});ZBSearch supports sorting on 'string', 'number' and 'boolean'. The arrays are not supported.
You can also specify nested properties using the '.' notation: 'meta.tag', 'meta.rating' and 'meta.favorite'. For example:
const results = search(db, {
term: "prestige",
sortBy: {
property: "meta.rating",
},
});Reverse order
ZBSearch supports the reverse order specifying the key order:
const db = create({
schema: {
title: "string",
year: "number",
inPromotion: "boolean",
meta: {
tag: "string",
rating: "number",
favorite: "boolean",
},
},
});
const results = search(db, {
term: "prestige",
sortBy: {
property: "title", // or 'year', 'inPromotion'
order: "DESC", // default is "ASC"
},
});Memory optimization
By default, ZBSearch allows the sort on all properties defined in the schema.
This creates an in-memory sort index for each properties.
If you want to optimize the memory usage, ZBSearch supports the unsortableProperties list.
const db = create({
schema: {
title: "string",
year: "number",
inPromotion: "boolean",
meta: {
tag: "string",
rating: "number",
favorite: "boolean",
},
},
sortBy: {
unsortableProperties: ["year", "meta.tag"],
},
});Custom sort
ZBSearch allows you to specify the sort algorithm in the following way:
const db = create({
schema: {
title: "string",
year: "number",
inPromotion: "boolean",
meta: {
tag: "string",
rating: "number",
favorite: "boolean",
},
},
sortBy: (a, b) => {
// Implement the custom sort algorithm
return a[2].year - b[2].year;
},
});The function accepts 2 parameter with the following format [string, number, Document] that stands for:
- id of the document
- score of the document
- the document
Disable sort
You can disable the sort functionality using the following snippet:
const db = create({
schema: {
// The schema
},
sort: {
enabled: false,
},
});