angularalgoliainstantsearch.js

How to get specific data from algolia in angular


I'm using algolia in angular.
I'm trying to get only a specific record from algolia.
I have a product_id and want record of that product_id
Here is what I have done so far -
.html file

    <ais-instantsearch [conproducts]>
        <ais-configure [searchParameters]="{ hitsPerPage: 1 }"></ais-configure>
        <ais-hits>
           <ng-template let-hits="hits">
           <div class="row">
                <div class="col-lg-2 col-md-3 col-sm-4 col-6"*ngFor="let hit of hits">
                    {{hit.name}}
                 </div>
           </div>
           </ng-template>
         </ais-hits>
    </ais-instantsearch>

.ts file

    const searchClient = algoliasearch(
      environment.algolia_application_id,
      environment.algolia_search_api_key
    );
    
    export class ProductsComponent implements OnInit {
      productsConfig = {
          indexName: 'products',
          searchClient
      };
    }

How to get specific data by id in the algolia?
Any help would be appreciated,
Thanks


Solution

  • If you're trying to only retrieve a specific record by an attribute from your Algolia index, you can use filters. For example, let's say you want to retrieve a record which product_id is "abcdef", you can set a filter on your ais-configure component like the following:

    <ais-configure
      [searchParameters]="{ filters: 'product_id:abcdef' }"
    ></ais-configure>
    

    Note that your product_id attribute must be set in attributesForFaceting for it to be filterable. You can use the filterOnly modifier if you only need to use it as a filter and never as a facet, for better performance. This needs to be done at the index level, either from your indexing code or directly in the Algolia dashboard. You can follow this guide to learn how to do it.