reactjs - Algolia api how to write api filter for nested fields - Stack Overflow

admin2025-04-28  2

This is my algolia entry I want to search for, in my website i have state filters the user can select to get courses available from these states. Here's an example of an entry:

{
  "id": 4,
  "title": "again",
  "description": "Hello do you see me",
  "author": "cool",
  "level": "Advanced",
  "type": "Live Course",
  "price": 7700,
  "trial": false,
  "practice_areas": [
    {
      "id": 1,
      "name": "Cool"
    }
  ],
  "cle_credits": [
    {
      "id": 3,
      "credits": 12,
      "state": {
        "id": 1,
        "name": "Kentucky"
      },
      "cle_type": {
        "id": 2,
        "name": "Paralegal"
      }
    },
    {
      "id": 4,
      "credits": 56,
      "state": {
        "id": 2,
        "name": "Kansas"
      },
      "cle_type": {
        "id": 1,
        "name": "Ethics"
      }
    }
  ],
  "objectID": "4"
}

How should I write my api url if I already used these and they don't work?

&currentPage=0&filters=state:Kansas &currentPage=0&filters=cle_credits.state.name:Kansas

Here's how I build my search url:

export const getSearchUrl = ({
                               currentPage,
                               type,
                               level,
                               states,
                               selectedPracticeArea
                             }: {
  currentPage?: number;
  type?: string;
  level?: string;
  states: string[];
  selectedPracticeArea: string[];
}) => {
  let url = '';
  let filters: string[] = [];

  if (currentPage || currentPage === 0) {
    url += `&currentPage=${currentPage}`;
  }

  if (type) {
    url += `&type=${type}`;
  }

  if (level) {
    url += `&level=${level}`;
  }

  if (states.length > 0) {
    const stateFilters = states
      .map(state => `cle_credits.state.name:${state}`)
      .join(' OR ');
    filters.push(`${stateFilters}`);
  }

  if (selectedPracticeArea.length > 0) {
    const practiceFilters = selectedPracticeArea
      .map(practice => `practice_areas.name:"${practice}"`)
      .join(' OR ');
    filters.push(`(${practiceFilters})`);
  }

  if (filters.length > 0) {
    url += `&filters=${encodeURIComponent(filters.join(' AND '))}`;
  }

  console.log('url', url);

  return url;
};

So how can I fix this issue to be able to search properly by state?

转载请注明原文地址:http://anycun.com/QandA/1745781928a91215.html