Query text

Find the indexed files that are the most similar to the query text.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

Python

def query(index_file, text, n_top=3):
    """Find the indexed files that are the most similar to
    the query text.
    """

    with io.open(index_file, "r") as f:
        index = json.load(f)

    # Get the categories of the query text.
    query_categories = classify(text, verbose=False)

    similarities = []
    for filename, categories in six.iteritems(index):
        similarities.append((filename, similarity(query_categories, categories)))

    similarities = sorted(similarities, key=lambda p: p[1], reverse=True)

    print("=" * 20)
    print("Query: {}\n".format(text))
    for category, confidence in six.iteritems(query_categories):
        print("\tCategory: {}, confidence: {}".format(category, confidence))
    print("\nMost similar {} indexed texts:".format(n_top))
    for filename, sim in similarities[:n_top]:
        print("\tFilename: {}".format(filename))
        print("\tSimilarity: {}".format(sim))
        print("\n")

    return similarities

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.