Untitled

mail@pastecode.io avatar
unknown
plain_text
6 days ago
3.6 kB
5
Indexable
Never
import boto3
from pydantic import BaseModel
from typing import List
import json

class UserPrompt(BaseModel):
    query: str

class CustomerSearchResultItem(BaseModel):
    lookup_id: str
    lookup_value: str
    linked_records: List[str]

class CustomerSearchResults(BaseModel):
    hits: List<CustomerSearchResultItem]
    found: int

class CustomerSearchParameters(BaseModel):
    query: str
    fields: List[str] = ["lookup_id", "lookup_value"]
    sort: str = '_score desc'
    size: int = 10

class CustomerCloudSearchClient:
    def __init__(self, domain_endpoint: str):
        self.client = boto3.client('cloudsearchdomain', endpoint_url=domain_endpoint, region_name="us-east-1", aws_access_key_id="YOUR_AWS_ACCESS_KEY_ID", aws_secret_access_key="YOUR_AWS_SECRET_ACCESS_KEY")

    def search(self, params: CustomerSearchParameters) -> CustomerSearchResults:
        response = self.client.search(
            query=params.query,
            queryParser='simple',
            sort=params.sort,
            size=params.size,
            queryOptions=json.dumps({"fields": params.fields})
        )
        search_results = []
        for hit in response['hits']['hit']:
            search_results.append(CustomerSearchResultItem(
                lookup_id=hit['fields'].get('lookup_id', [''])[0],
                lookup_value=hit['fields'].get('lookup_value', [''])[0],
                linked_records=hit['fields'].get('linked_records', [])
            ))

        return CustomerSearchResults(
            hits=search_results,
            found=response['hits']['found']
        )
    
def format_customer_search_results(customer_search_results: CustomerSearchResults, keyword: str) -> List[dict]:
    """
    Formats the customer search results into a list of dictionaries representing each result item.
    
    Args:
    - customer_search_results (CustomerSearchResults): The customer search results object containing customer information.
    - keyword (str): The keyword used for the search.

    Returns:
    - list: List of dictionaries, each representing a formatted customer search result.
    """
    formatted_results = []

    for item in customer_search_results.hits:
        # Format matches list
        matches = [
            {
                "query_by_value": item.lookup_id,
                "lookup_value": item.lookup_value,
                "user_friendly_value": ""
            }
        ]

        # Construct formatted result dictionary
        formatted_result = {
            "type": "customer",
            "index_name": "fincopilot-dim-customer",
            "total_count": customer_search_results.found,
            "extracted_count": len(matches),
            "matched_on": keyword,
            "matches": matches
        }

        formatted_results.append(formatted_result)

    return formatted_results
    
def handle_user_prompt_for_Customer(user_prompt: UserPrompt, field: str) -> CustomerSearchResults:
    with open('config.json', 'r') as f:
        config = json.load(f)
    client = CustomerCloudSearchClient(config['CUSTOMER_DOMAIN_ENDPOINT'])
    params = CustomerSearchParameters(query=user_prompt.query, fields=[field])
    results = client.search(params)
    return results

if __name__ == "__main__":
    # Replace with your CloudSearch domain endpoint
    query = "Australia"
    user_prompt = UserPrompt(query=query)
    results = handle_user_prompt_for_Customer(user_prompt, field='lookup_value')
    formatted_results = format_customer_search_results(results, query)
    print(formatted_results)
Leave a Comment