Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppSync - query for all items created within a date range?

I'm trying to query my items (which have fields of AWS DateTime of CreatedAt and UpdatedAt) for all within a certain date range. For example, the past 48 hours.

For example, using this schema:

type Note @model @searchable @auth(rules: [{ allow: owner }]) {
  id: ID!
  note: String
  createdAt: AWSDateTime

I'm able to search for dates using, for example:

query {
  searchNotes(filter:{createdAt: { matchPhrasePrefix: "2018-12-27"}}) {
    items{
      id
        title
      createdAt
    }
  }
}

Which returns all notes that match the UTC time with that string prefix.

From which, I have to sort myself using moment.diff(), or some other method.

I'm not sure there is a better/more efficient way of doing searching/filtering by dates and time using AppSync and GraphQl?

Thank you.

like image 544
Stephen A. Lizcano Avatar asked Jan 02 '19 09:01

Stephen A. Lizcano


2 Answers

You can use this query to filter 2 AWSDateTime:

query {
  searchNotes(filter:{createdAt: { between: ["2018-12-27T00:00:00", "2019-01-27T00:00:00"]}}) {
    items{
      id
        title
      createdAt
    }
  }
}

like image 192
agua from mars Avatar answered Sep 16 '22 11:09

agua from mars


As of writing (Jan 3, 2019), the easiest way to do this would be to store the date as an integer (e.g. seconds since epoch) which would open up the gt, lt, gte, ... filter fields on the auto-generated search resolvers filter input.

Another solution is to write your own resolver using the AWS AppSync console or your own CloudFormation stack. When writing your own resolver you can leverage the entire Elasticsearch DSL to implement all kinds of queries (see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html). To go down this route, you can add your own search field to the Query type in your schema and write a custom resolver.

type Query {
  searchNotesByCreatedAt(start: String!, end: String!): NotesConnection
}

Then via the console or via your own CloudFormation stack you can write a resolver like this:

{
  "version": "2017-02-28",
  "operation": "GET",
  "path": "/note-<your-api-id>/doc/_search", // created by amplify
  "params": {
    "body": {
      "sort": [{ "createdAt" : {"order" : "desc"}}],
      "query": {
        "range" : {
            "createdAt" : {
                "gte": $ctx.args.start, 
                "lte": $ctx.args.end
            }
        }
      }
    }
  }
}

You will only need to deploy this resolver using the console or your own CF stack temporarily. Work is being done to allow you to write your own resolvers from within the amplify CLI. For more information on how this will work see https://github.com/aws-amplify/amplify-cli/issues/574.

Let me know if this works for you.

like image 31
mparis Avatar answered Sep 18 '22 11:09

mparis