'typeorm mongo full text search - sort with $meta: "textScore"
I'm using typeorm to connect on mongodb, Is typeorm support sort on relevant score return from full text search mongodb? Like described here.
from mongo, i want to make query as:
db.todos.find( {$text: { $search: "coffee" }}, {score: { "$meta": "textScore" }}) .sort({score: { "$meta": "textScore" }}) .limit(20);
How can i query from MongoRepository from typeorm? Thank you.
Solution 1:[1]
I've tested the following code and it works:
await todoRepository.find({
where: {
$text: { $search: 'search query here' },
},
take: 20
});
P.S. You need to ensure you have a text index on a field in the Todo collection.
I'm not sure if sorting by score is working properly with TypeORM. I haven't got any success so far.
Solution 2:[2]
I've been working a full day to discover how to make this mongo query work the same way on typeorm. Here's the result of this:
On the schema file, you need to put on the field that you configure your index at mongo @Index({ fulltext: true }) like this (in my case I use the field Title):
@Index({ fulltext: true })
@Column()
title: string;
Inside the order option from method find, you add ['score']: { $meta: "textScore" }, the score its the field that mongo generate when you`re trying to search by index.
If you need, you can add others kind of filters too inside the order.
And the function find will be like this:
const announcements = await this.ormRepository.find({
where: {
$text: { $search: 'search query here' }
},
//@ts-ignore
order: { ['boosted']: 'DESC', ['score']: { $meta: "textScore" } },
select: ['id', 'title', 'images', 'address', 'categories'],
take: 50,
});
I add the //@ts-ignore because I wasnt able to type this field because it doesnt exist until the search has been done on mongo, so I just ignore, because the order expect the types 1, -1, undefined, 'ASC' and 'DESC', but it's working very well this way, ordering by score.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | J.F. |
| Solution 2 | ouflak |
