Search code examples
typescriptamazon-dynamodbdynamodb-queries

ValidationException: Query condition missed key schema element: company'


Query that searches the db for a type 'Company' with the 'Country' field as passed in as an argument, and returns this Company object.

export const companyQuery = async (country: string): Promise<Company> => {
  const queryParams: DocumentClient.QueryInput = {
    TableName: process.env.DATABASE,
    IndexName: 'type-company-GSI',
    KeyConditionExpression: '#type = :type AND #country = :country',
    ExpressionAttributeNames: {
      '#country': 'country',
      '#type': 'type',
    },
    ExpressionAttributeValues: {
      ':country': country,
      ':type': 'Company',
    },
  };
  Logger.Log(
    'LOGGER COMPANY QUERY ' + (await Database.query<Company>(queryParams))[0],
  );
  return (await Database.query<Company>(queryParams))[0];
};

Since my logs didn't show the log in this piece of code, it isn't getting that far. The code that calls this function threw a ValidationException: Query condition missed key schema element: company . Not quite sure what that means or what I'm supposed to change.


Solution

  • The Query request is used to scan part of a single partition, not the entire table (for that, you have the Scan request. This means that KeyConditionExpression must include an equality condition with your partition-key attribute. The error message suggests that company is your partition key attribute, and it is missing in the KeyConditionExpression.

    Note that your query specifies a GSI in IndexName, which has its own key columns, and you must use those in KeyConditionExpression. Maybe you used the wrong GSI in this query, or shouldn't have used a GSI at all?