Graphql querying multipe fields without a required field

Trying to create a query that filter out by passing in arg with only city , only state or both

type Data {
    city: String!,
    state: String!
}
type Query {
    filterByCityOrState(city: String, state: String): [Data!]
}

Query only works when both fields have value

query filterByCandS{
  filterByCityOrState(city:"sf", state: "ca"){
    data{
      _id
    }
  }
}

if only city or state passed in will return empty array seems like there is a really easy solution to this but i couldnt find in anywhere … pretty new to this please advice

Hi @allencwwong, and welcome!

When you pass in null as an Index argument it doesn’t ignore the argument, it looks for a “match” with null – which really means it matches when the document does not have that field. If all of your Data Documents have both fields (they should, you’ve marked both of them as NonNull types), then the filterByCityOrState Index will always return empty results when you pass null as an argument.

To accomplish what you are trying you will need to create a customer resolver using the @resolver directive. The UDF for your resolver can use logic to determine which Index to use.

type Query {
  # specifying the following fields will create Indexes of the same name,
  # which can be used in our custom resolver
  filterByCity(city: String!): [Data!]
  filterByState(state: String!): [Data!]
  filterByCityAndState(city: String!, state: String!)

  # custom resolver
  filterByCityOrState(city: String, state: String): [Data!] @resolver
}
CreateFunction({
  name: "filterByCityOrState",
  body: Query(Lambda(
    ["city", "state"],
    Let(
      {
        match: If(
          IsNull(Var("city")),
          Match(Index("filterByState"), Var("state")),
          If(
            IsNull(Var("state")),
            Match(Index("filterByCity"), Var("city")),
            Match(Index("filterByCityAndState"), Var("city"), Var("state"))
          )
        ),
        results: Paginate(Var("match"))
      },
      Select(["data"], Var("results"), [])
    )
  ))
})

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.