GraphQL 如何支持 AND-OR 查询条件?
How does GraphQL support AND-OR query conditions?
我是 GraphQL 的新手。要求从CUSTOMERS table查询所有符合条件的数据,满足条件:GENDER == 'MALE' or 'AGE' >= 20。它的GQL应该是什么样的?
您需要定义查询、模式和解析器。您的查询将类似于:
type Query {
nameItAsPerUsecase: Customer
}
架构将如下所示:
type Customer{
name : String
age: Int
.. add more fields as per as your need
}
您的解析器将是这样的:-
@Component
public class CustomerQuery implements GraphQLQueryResolver {
@Autowired
private CustomerRepository customerRepository ;
public Customer getNameItAsPerUsecase() {
return customerRepository.findByGenderAndAgeGreaterThanEqual(String gender, int age);
}
}
有人提议similar thing before but it is rejected。这意味着 GraphQL 本身不支持它,你必须自己推出它。
根据我所见,有几种方法可以做到:
(1) 定义您自己的查询语言,例如 Whosebug or Shopify 的作用:
type Query{
customers (query:String) : [Customer]
}
查询变为:
{
customers (query : "GENDER == 'MALE' or 'AGE' >= 20"){
id
name
}
}
(2)定义你自己的输入对象模型,可以涵盖所有需要的搜索需求。Prisma try to define one in OpenCRUD规范。你可以看看它的想法。例如,您可以定义一个输入模型:
input CustomerFilter {
AND : [CustomerFilter]
OR : [CustomerFilter]
# Define the fields that you support to search
gender : String
gender_not : String
....
....
...
...
age : Int
age_gte : Int
}
type Query{
customers (filter:CustomerFilter) : [Customer]
}
查询变为:
{
customers (filter : {
OR: [
{ gender : 'MALE' } ,
{ age_gte: 20 }
]
}){
id
name
}
}
This是另一种过滤模型,供参考。这个想法是对其进行量身定制,使其足以处理您所有的应用程序需求,而不会引入任何不必要的过滤复杂性。
另外,如果分页可能 return 许多数据,您很可能需要考虑分页之类的东西。这意味着你必须为每个查询的输入参数添加一个偏移量和限制,以某种方式限制记录的数量 returned 如果你正在做基于偏移量的分页或者看看 Relay Specification 如果你想以基于光标的分页样式进行。
我是 GraphQL 的新手。要求从CUSTOMERS table查询所有符合条件的数据,满足条件:GENDER == 'MALE' or 'AGE' >= 20。它的GQL应该是什么样的?
您需要定义查询、模式和解析器。您的查询将类似于:
type Query {
nameItAsPerUsecase: Customer
}
架构将如下所示:
type Customer{
name : String
age: Int
.. add more fields as per as your need
}
您的解析器将是这样的:-
@Component
public class CustomerQuery implements GraphQLQueryResolver {
@Autowired
private CustomerRepository customerRepository ;
public Customer getNameItAsPerUsecase() {
return customerRepository.findByGenderAndAgeGreaterThanEqual(String gender, int age);
}
}
有人提议similar thing before but it is rejected。这意味着 GraphQL 本身不支持它,你必须自己推出它。
根据我所见,有几种方法可以做到:
(1) 定义您自己的查询语言,例如 Whosebug or Shopify 的作用:
type Query{
customers (query:String) : [Customer]
}
查询变为:
{
customers (query : "GENDER == 'MALE' or 'AGE' >= 20"){
id
name
}
}
(2)定义你自己的输入对象模型,可以涵盖所有需要的搜索需求。Prisma try to define one in OpenCRUD规范。你可以看看它的想法。例如,您可以定义一个输入模型:
input CustomerFilter {
AND : [CustomerFilter]
OR : [CustomerFilter]
# Define the fields that you support to search
gender : String
gender_not : String
....
....
...
...
age : Int
age_gte : Int
}
type Query{
customers (filter:CustomerFilter) : [Customer]
}
查询变为:
{
customers (filter : {
OR: [
{ gender : 'MALE' } ,
{ age_gte: 20 }
]
}){
id
name
}
}
This是另一种过滤模型,供参考。这个想法是对其进行量身定制,使其足以处理您所有的应用程序需求,而不会引入任何不必要的过滤复杂性。
另外,如果分页可能 return 许多数据,您很可能需要考虑分页之类的东西。这意味着你必须为每个查询的输入参数添加一个偏移量和限制,以某种方式限制记录的数量 returned 如果你正在做基于偏移量的分页或者看看 Relay Specification 如果你想以基于光标的分页样式进行。