From e903150fd4164d07ea4af5edd60deab952bbbfb9 Mon Sep 17 00:00:00 2001 From: Dustin Thomas Date: Tue, 20 Feb 2024 10:33:01 -0600 Subject: [PATCH] Add functions for connecting to Meilisearch and adding documents --- search.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/search.py b/search.py index e69de29..b45934a 100644 --- a/search.py +++ b/search.py @@ -0,0 +1,49 @@ +"""Interactions with the Meilisearch API for adding and searching cables.""" +from meilisearch import Client +from meilisearch.task import TaskInfo +import json + +DEFAULT_URL = "http://localhost:7700" +DEFAULT_APIKEY = "fluffybunnyrabbit" # I WOULD RECOMMEND SOMETHING MORE SECURE +DEFAULT_INDEX = "cables" + + +class JukeboxSearch: + """Class for interacting with the Meilisearch API.""" + def __init__(self, url: str = None, api_key: str = None, index: str = None): + """Connect to Meilisearch and perform first-run tasks as necessary. + + :param url: Address of the Meilisearch server. Defaults to ``http://localhost:7700`` if unspecified. + :param api_key: API key used to authenticate with Meilisearch. It is highly recommended to set this as something + secure if you can access this endpoint publicly, but you can ignore this and set Meilisearch's default API key + to ``fluffybunnyrabbit``. + :param index: The name of the index to configure. Defaults to ``cables`` if unspecified.""" + # connect to Meilisearch + url = url or DEFAULT_URL + api_key = api_key or DEFAULT_APIKEY + self.index = index or DEFAULT_INDEX + self.client = Client(url, api_key) + # create the index if it does not exist already + if self.client.get_index(self.index) is None: + self.client.create_index(self.index) + + def add_document(self, document: dict) -> TaskInfo: + """Add a cable to the Meilisearch index. + + :param document: Dictionary containing all the cable data. + :returns: A TaskInfo object for the addition of the new document.""" + return self.client.index(self.index).add_documents(document) + + def add_documents(self, documents: list): + """Add a list of cables to the Meilisearch index. + + :param documents: List of dictionaries containing all the cable data. + :returns: A TaskInfo object for the last new document.""" + taskinfo = None + for i in documents: + taskinfo = self.add_document(i) + return taskinfo + + def query(self): + """Execute a search query on the Meilisearch index.""" + pass