user10470680
user10470680

Reputation: 41

Fulltext mongodb $text search query in graphql-compose-mongoose

I'm unable to figure out how to construct a graphql query for performing the mongodb fulltext search using the text index. https://docs.mongodb.com/manual/text-search/

I've already created a text index on my string in the mongoose schema but I don't see anything in the schemas that show up in the grapqhl playground.

Upvotes: 2

Views: 762

Answers (1)

Isaac Oluwatemilorun
Isaac Oluwatemilorun

Reputation: 576

A bit late, though I was able to implement it like so

const FacilitySchema: Schema = new Schema(
    {
        name: { type: String, required: true, maxlength: 50, text: true },
        short_description: { type: String, required: true, maxlength: 150, text: true },
        description: { type: String, maxlength: 1000 },
        location: { type: LocationSchema, required: true },
    },
    {
        timestamps: true,
    }
);

FacilitySchema.index(
    {
        name: 'text',
        short_description: 'text',
        'category.name': 'text',
        'location.address': 'text',
        'location.city': 'text',
        'location.state': 'text',
        'location.country': 'text',
    },
    {
        name: 'FacilitiesTextIndex',
        default_language: 'english',
        weights: {
            name: 10,
            short_description: 5,
            // rest fields get weight equals to 1
        },
    }
);

After creating your ObjectTypeComposer for the model, add this

const paginationResolver = FacilityTC.getResolver('pagination').addFilterArg({
    name: 'search',
    type: 'String',
    query: (query, value, resolveParams) => {
        resolveParams.args.sort = {
            score: { $meta: 'textScore' },
        };
        query.$text = { $search: value, $language: 'en' };
        resolveParams.projection.score = { $meta: 'textScore' };
    },
});

FacilityTC.setResolver('pagination', paginationResolver);

Then you can assign like so


const schemaComposer = new SchemaComposer();

schemaComposer.Query.addFields({
   // ...
   facilities: Facility.getResolver('pagination')
   // ...
});

On your client side, perform the query like so

{
  facilities(filter: { search: "akure" }) {
    count
    items {
      name
    }
  } 
}

Upvotes: 5

Related Questions