Reputation: 898
How to search documents on an attribute?
For example: we have a collection of cities and we want to search by their name attribute
Upvotes: 1
Views: 939
Reputation: 898
I felt that this topic is not well covered so I will post a working example.
You have to create an index on a list of ngrams of the attribute you want to search.
CreateIndex({
name: 'cities_by_ngrams',
source: [
{
// If your collections have the same property that you want to access you can pass a list to the collection
collection: [Collection('cities')],
fields: {
wordparts: Query(
Lambda('city',
Distinct(
Union(
Let(
{
ngrams: q.Map(
// ngrams
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
Lambda('i', NGram(
LowerCase(Select(['data', 'name'], Var('city'))),
Var('i'),
Var('i'),
)
)
)
},
Var('ngrams')
)
)
)
)
)
}
}
],
terms: [
{
binding: 'wordparts'
}
]
})
and then search with pagination
Map(
Paginate(Match(Index('cities_by_ngrams'), 'londo')),
Lambda('ref', Get(Var('ref')))
)
a simpler way is to have a list of ngrams you plan to search on for every document, and then create an index on that field. The downside is that you will have to exclude that field wherever you don't need it.
Upvotes: 4