Google News
logo
TinyDB - Interview Questions
How do you perform full-text search in TinyDB?
TinyDB does not natively support full-text search capabilities out of the box. However, you can implement basic full-text search functionality by iterating over the documents in a table and manually filtering based on text matching criteria. Here's a basic approach to perform full-text search in TinyDB:
from tinydb import TinyDB, Query

# Create a new TinyDB instance with JSON file storage
db = TinyDB('db.json')

# Get a reference to the 'documents' table
documents_table = db.table('documents')

# Define a Query object to specify the query condition
Document = Query()

def full_text_search(query_string):
    # Perform full-text search by iterating over documents and filtering based on text matching criteria
    matching_documents = []
    for document in documents_table.all():
        # Check if the query string is found in any field of the document
        if any(query_string.lower() in str(value).lower() for value in document.values()):
            matching_documents.append(document)
    return matching_documents

# Example usage: Perform a full-text search for documents containing the word 'Python'
results = full_text_search('Python')
for document in results:
    print(document)?
In this example :

* We define a function full_text_search() that takes a query string as input and performs a full-text search on the documents in the 'documents' table.

* Inside the function, we iterate over all documents in the table using the all() method.

* For each document, we check if the query string is found in any field of the document by iterating over the values and performing a case-insensitive search using the in operator.

* If the query string is found in any field of the document, we add the document to the list of matching documents.

* Finally, we return the list of matching documents.
Advertisement