Skip to content

Amazon Bedrock Knowledge Bases with metadata filtering

0

I'd like to do a metadata filtering (to be used in the retrieve_and_generate method) based on the file names of the files saved in the S3 bucket that is part of the knowledge bases. Tried to follow this blog https://aws.amazon.com/blogs/machine-learning/amazon-bedrock-knowledge-bases-now-supports-metadata-filtering-to-improve-retrieval-accuracy/ but the scripts are not complete. I'm looking specifically in this example, because it seems that fit my use case. Thank you.

publisher_filter = { "startsWith": { "key": "x-amz-bedrock-kb-source-uri", "value": "s3://$bucket_name/video_game/neo_tokyo_games/" } }

3 Answers
0

Here's one way of doing it through using the Boto3 to access the Bedrock SDK in Python (code is in quotation marks).

import boto3 

bedrock_cli = boto3.client("bedrock", region_name="your-region-name")
bucket_name = "name of bucket"
prefix = " "

metadata_filter = {
      "startsWith": {
             "key": "x-amz-bedrock-kb-source-uri",
             "value": f"s3://{bucket_name}/{prefix}"
       }
}

response = bedrock_cli.retrieve_and_generate(
    knowledgeBaseId="your-knowledge-base-id",  # Replace with your Knowledge Base ID
    inputText="Tell me about Neo Tokyo games.",
    maxResults=5,  # Adjust to your needs
    metadataFilters=[metadata_filter]
)

Make sure your S3 metadata filter matches the filter key. Make sure to tag them correctly when they are uploaded into the S3 bucket.

Hope the code above helps!

answered 2 years ago

  • can you explain what goes in here: "key": "x-amz-bedrock-kb-source-uri"? Also, what you didnt explain is how to create a dynamic metadata filter expression based off my file names. Say I want to only look for answers in three of my files in the S3 bucket. How can I build an expression that will lists all these files names using your metadata_filter? something like: def create_file_name_filter(documents): bucket_name = "marketoutlook-2025" return { "orAll": [ { "startsWith": { "key": "still do not know what goes in here?", #please explain what goes in here...... "value": f"s3://{bucket_name}/{doc]}" } } for doc in documents ] }

  • @Brunn Upon creating the Knowledge Base, you'll create a Vector Database, usually Amazon OpenSearch Service, when you discover your fields, several fields will be used for retrieval by the Bedrock agent as Metadata, "x-amz-bedrock-kb-source-uri" is one of them.

0

Amazon Bedrock Knowledge Bases indeed supports metadata filtering, which can be used to improve retrieval accuracy by narrowing down search results based on specific document attributes. In your case, you're looking to filter based on file names in the S3 bucket that is part of your knowledge base.

The example you provided is correct and can be used to filter documents based on their S3 prefix. This approach leverages the built-in metadata attribute "x-amz-bedrock-kb-source-uri" which represents the S3 URI of the document. By using the "startsWith" operator, you can filter documents that are located in a specific folder within your S3 bucket.

Here's how you can use this filter in the retrieve_and_generate method:

  1. First, construct your filter as you've shown:

    publisher_filter = { "startsWith": { "key": "x-amz-bedrock-kb-source-uri", "value": "s3://$bucket_name/video_game/neo_tokyo_games/" } }

  2. Then, when calling the retrieve_and_generate method, include this filter in your request:

    response = bedrock_runtime.retrieve_and_generate( knowledgeBaseId='your-knowledge-base-id', input={ 'text': 'Your query here', 'retrievalConfiguration': { 'vectorSearchConfiguration': { 'filter': publisher_filter } } }, # other parameters as needed )

This approach will filter your retrieval to only include documents from the specified S3 prefix, which in this case is the "neo_tokyo_games" folder within your "video_game" directory.

Remember that the S3 prefix filtering is just one way to use metadata filtering. You can also define custom metadata for each document when ingesting data into the knowledge base, which allows for more flexible and specific filtering options based on your particular use case.

If you need to apply more complex filters or combine multiple conditions, you can use other operators like "andAll" or "orAll" to create more sophisticated filtering logic.

Sources
Amazon Bedrock Knowledge Bases now supports metadata filtering to improve retrieval accuracy | AWS Machine Learning Blog
Knowledge Bases for Amazon Bedrock now supports metadata filtering to improve retrieval accuracy | AWS Machine Learning Blog
RetrievalFilter - Amazon Bedrock

answered 2 years ago

  • Hey I have a similar use case, I am using this start with filter to find specific user's folder in my s 3 bucket, however if the filter finds nothing, instead of returning en empty array its basically giving out other users folders too, can you help with this please?

0

Hey I have a similar use case, I am using this start with filter to find specific user's folder in my s 3 bucket, however if the filter finds nothing, instead of returning en empty array its basically giving out other users folders too, can you help with this please?

answered 2 years ago

  • You should manage it via Instructions for the Agent. An instruction like: "Important Rule: Do not mention any other person's name or data if you cannot access the current user data."

    The response would be something like this for a user named "Test": "I cannot provide any information under the name "Test". For security and privacy reasons, I can only provide information from documents that match your authenticated username. If you believe you should have access to your financial data, please ensure you're using the correct username or contact support for assistance."

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.