How to search a query and group by facet count?

How can I search (in python or any other language) for a query in algolia and get out the number of items that match the query in each facet? I know you can see this value(s) in the console so was wondering how I could possibly create that in code. It’s like SQL GROUPBY for a facet, and you get the COUNT for each distinct facet. So I’m not interested in the actual data, just want the counts.

I’ve been calling results = index.search('query', { 'distinct': True }) But I still seem to only get data results back in my db. Do I need to change the settings for my index? (Only have read permissions atm).

Hi eKairos,

I do this in ruby using:

        def get_facets(index, facet_names = '*')
          index_init(index).search('*', facets: facet_names, responseFields: 'facets') || { facets: {} }
        end

I have a Postman API request for this - here is the cURL:

import requests

url = "https://{APP_ID}-dsn.algolia.net/1/indexes/{INDEX_NAME}"

querystring = {"query":"*","facets":"*","responseFields":"facets"}

payload = ""
headers = {
    'X-Algolia-API-Key': "{API_KEY}",
    'X-Algolia-Application-Id': "{APP_ID}"
    }

response = requests.request("GET", url, data=payload, headers=headers, params=querystring)

print(response.text)

You will get a facets hash in ruby => Probably a map in python :+1:

You will need to traverse the Map and get a count of facet matches - but this works quite fast :+1:

{
    "facets",
    {
        "facet_name":
        {
            "facet_value": xxx < number of matches
        }
    }
}

Example:

{
    "facets": {
        "category_ids": {
            "1": 6,
            "2": 6,
            "3": 6
        },
        "current_price": {
            "10.0": 2,
            "0.43": 1,
            "0.46": 1,
            "0.76": 1
        },
        "product_rating": {
            "0": 206,
            "1": 9,
            "2": 6,
            "3": 6,
            "4": 7,
            "5": 3
        }
    }
}

Sum the right hand side for the count :+1:

:wink: Simon