Coder Social home page Coder Social logo

Comments (6)

chrisbonifacio avatar chrisbonifacio commented on June 3, 2024 1

Closing this as not a bug, but more of a question. While AppSync supports query batching, making use of it would require manually writing the graphql string. Using the client.graphql API, you can pass in a custom string to the query parameter to combine the calls into one query and thus one network call.

You can try this but it would still result in two separate operations in DynamoDB because each query maps to one can only map to one resolver which can only map to one DynamoDB operation.

Otherwise, in the Gen 2 client.models API, you would have to split up the queries into separate calls:

schema

  Message: a
    .model({
      senderId: a.string().required(),
      receiverId: a.string().required(),
      viewedTimeStamp: a.timestamp().required(),
      content: a.string().required(),
      status: a.string().required(),
      createdAt: a.datetime().required(),
    })
    .authorization((allow) => [
      allow.ownerDefinedIn("senderId"),
      allow.ownerDefinedIn("receiverId").to(["read"]),
    ])
    .secondaryIndexes((index) => [
      index("senderId").sortKeys(["viewedTimeStamp"]),
      index("receiverId").sortKeys(["viewedTimeStamp"]),
    ]),

queries

    const { data: recieveUnreadMessages } =
      await client.models.Message.listByReceiverIdAndViewedTimeStamp({
        receiverId: currentUser.userId,
        viewedTimeStamp: {
          attributeExists: false,
        },
      });

    const { data: sentUnreadMessages } =
      await client.models.Message.listBySenderIdAndViewedTimeStamp({
        senderId: currentUser.userId,
        viewedTimeStamp: {
          attributeExists: true,
        },
      });

    console.log({ recieveUnreadMessages, sentUnreadMessages });

Unfortunately DynamoDB only accepts one filter expression per Scan/Query so at least two different operations must occur.

from amplify-js.

cwomack avatar cwomack commented on June 3, 2024

Hello again, @ChristopherGabba 👋. Appreciate you providing details on your queries, schema, and code snippet already. At first glance, it sounds like Compound Filters might be able to accomplish what you're looking for to allow your queries to be combined into a single one with and, or, and not Boolean logic. Have you tried incorporating this yet?

Also, is your viewedTimestamp: AWSDateTime within your schema intended to have both the sender AND the receiver have only 1 shared value for viewedTimestamp?

from amplify-js.

cwomack avatar cwomack commented on June 3, 2024

@ChristopherGabba, wanted to check in and see if you're still blocked by this or had a chance to review the above comment.

from amplify-js.

ChristopherGabba avatar ChristopherGabba commented on June 3, 2024

@cwomack I think your Compound Filters link is broken and just takes me back to this issue page. Regardless, I think I found some information on the topic. I previously was using compound filters with multiple ors and ands but ran into an issue with the limit filter. Eventually I stumbled across using the secondary @index to improve your query efficiencies, although I'm no expert on this topic. That's why I eventually made two different queries using @Index. Going back to compound filters is of course possible, but is that better than what I'm doing now as far as query efficiency (database reads / writes / etc.)?

from amplify-js.

chrisbonifacio avatar chrisbonifacio commented on June 3, 2024

Hi @ChristopherGabba , generally leveraging secondary indexes are more efficient than using a list + compound filters because a list will trigger a Scan operation on the DynamoDB table whereas secondary indexes will perform a Query instead which is more cost effective.

Perhaps something like this might work for your use case?

Gen 2 Schema

  Message: a
    .model({
      senderId: a.id().required(),
      recieverId: a.id().required(),
      content: a.string().required(),
      status: a.string().required(),
      createdAt: a.datetime().required(),
    })
    .secondaryIndexes((index) => [
      index("senderId"),
      index("recieverId").sortKeys(["status", "createdAt"]),
    ]),

Client Query

image

from amplify-js.

ChristopherGabba avatar ChristopherGabba commented on June 3, 2024

@chrisbonifacio Thanks for providing this, I actually had not looked into Gen 2's API structure.

What I'm looking for essentially is a way for me to query messages in the most efficient way possible. If that is with two different secondary index calls (as shown in my example above), then that is what I'm looking to do.

I was just wondering if there is an even more efficient way to perform my "double" query like:

clients.models.Message.listUsersByReceiverOrSenderId({
     receiverOrSenderId: "123", // this effectively queries both situations above
     senderFilter: {
         viewedTimestamp: { attributeExists: true },
     },
     receiverFilter: {
        viewedTimestamp: { attributeExists: false },
     }
})

My situation is kind of unique. Effectively, my app sends a media to the user, the user looks at that media, and then it sends that same media back with a response. So when I query the database table for the actual user on the app, I am checking to see all items that have been sent by the user, but have been responded to, OR a message that this particular user is supposed to respond to.

My end goal is just to make sure that at scale, I'm being as efficient as possible with my queries using secondary indexes etc. in order to get all of my data back to the user.

from amplify-js.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.