如何使用Hasura GraphQL Engine实现多字段搜索查询?
Hasura真的是个游戏规则改变者!我刚接触它的时候,它还处于早期开发阶段,但现在功能已经丰富太多了,自定义能力拉满,还支持创建PostgreSQL函数和视图。我最近写了个函数,用来在Hasura GraphQL Engine里实现多字段搜索,连数组元素的搜索需求都能满足,分享给大家~
自定义PostgreSQL搜索函数
这个函数支持按国家、性别、婚姻状态、宗教(数组格式)、年龄范围来筛选用户资料,所有参数都设了默认值,不用的条件可以直接留空:
CREATE OR replace FUNCTION search_profiles( _country text default null, _gender text default null, _marital_status text default null, _religion text[] default null, _age_start integer default null, _age_end integer default null ) returns setof profile AS $$ SELECT * FROM profile WHERE ((extract(year FROM age(CURRENT_TIMESTAMP, dob)) >= _age_start AND extract(year FROM age(CURRENT_TIMESTAMP, dob)) <= _age_end) OR _age_start IS NULL) AND (living_country LIKE _country OR _country IS NULL) AND (gender = _gender OR _gender IS NULL) AND (marital_status LIKE _marital_status OR _marital_status IS NULL) AND (religion IN (select unnest(_religion)) OR _religion IS NULL) $$ language sql stable;
对应的GraphQL查询示例
下面是调用这个函数的实际GraphQL查询,你可以根据自己的需求调整参数值和返回的字段列表:
query searchProfileQuery { search_profiles( args: { _country: "United Kingdom", _gender: "male", _marital_status: "Un Married", _religion: "{hindu, muslim}", _age_start: 20, _age_end: 29 }, order_by: {created_at: asc} ) { id income_currency last_name living_city living_country living_state marital_status mother_tongue nationality occupation religion } }
内容的提问来源于stack exchange,提问作者Aathi
相关产品推荐
相关产品推荐

