首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >graphql-compose-mongoose中的全文mongodb $text搜索查询

graphql-compose-mongoose中的全文mongodb $text搜索查询
EN

Stack Overflow用户
提问于 2020-04-04 01:34:56
回答 1查看 433关注 0票数 2

我不知道如何构造一个graphql查询来使用文本索引执行mongodb全文搜索。https://docs.mongodb.com/manual/text-search/

我已经在mongoose模式中的字符串上创建了一个文本索引,但是在grapqhl操场中显示的模式中看不到任何东西。

EN

回答 1

Stack Overflow用户

发布于 2020-09-28 00:20:23

有点晚了,尽管我能够像这样实现它

代码语言:javascript
复制
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
        },
    }
);

为模型创建ObjectTypeComposer后,添加以下内容

代码语言:javascript
复制
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);

然后,您可以像这样分配

代码语言:javascript
复制
const schemaComposer = new SchemaComposer();

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

在您的客户端,像这样执行查询

代码语言:javascript
复制
{
  facilities(filter: { search: "akure" }) {
    count
    items {
      name
    }
  } 
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61017389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档