Perform prefix search in DynamoDB

Introduction

DynamoDB-chan is convenient and cheaper than anything else, but it's not very easy to use when it comes to searching. Today I thought about how to do a prefix search with that, so I would like to summarize it. As I said in advance, Scan is used, so be careful not to overuse it.

First, the source code that was actually put into Lambda

lambda_function.py


import json
import boto3
from boto3.dynamodb.conditions import Attr

def lambda_handler(event, context):
    dynamoDB = boto3.resource("dynamodb")
    table = dynamoDB.Table(event["type"])
    title = event["title"]
    fin = title[0]+chr(ord(title[1])+2)

    queryData = table.scan(
      FilterExpression = Attr("Title").between(title,fin)
    )
    return queryData

What are you doing?

This prepares a character string in which the input character string and the second character of the input character string are shifted by two, and obtains the space between them. In the case of the song "Kyun" of Hinatazaka46 used for the test this time, first make the character string "Kyo" from the character string "Kyun". That is the next part. fin = title[0]+chr(ord(title[1])+2) All you have to do is scan the difference normally. By the way, in the case of "Kyun", it is as follows. image.png Since it is between "Kyun" and "Kyo", there are some songs that start with "Cue", but please be patient.

Finally

DynamoDB scan is messy and heavy because it narrows down the target data after acquiring all the records. If you can expect to be hit especially frequently, sign up for RDS obediently. I'm a pinchke developer, so I'll do my best with DynamoDB for a while.

Recommended Posts

Perform prefix search in DynamoDB
Binary search in Python
Linear search in Python
Binary search in Python (binary search)
Search for strings in Python
Search for strings in files
Binary search in Python / C ++
Algorithm in Python (binary search)
[Python] Get elements by specifying attributes with prefix search in BeautifulSoup
Write a binary search in Python
Perform Scala-like collection operations in Python
Algorithm in Python (depth-first search, dfs)
Write a depth-first search in Python
Depth-first search using stack in Python