Cannot Read Property '_ua' of Undefined Algolia Search
Coming from V1 (or js client v2)? Read the migration guide to the new version of the Helper.
Coming from V2? Read the migration guide to the new version of the Helper.
The JavaScript helper is an avant-garde library we provide to our users. If you lot are looking to build a complete search interface, we recommend yous to employ instantsearch.js. If you want to build an autocomplete menu, see autocomplete.js.
algoliasearch-helper-js
This module is the companion of the algolia/algoliasearch-customer-js. It helps you lot keep track of the search parameters and provides a higher level API.
See the helper in activity
- Features
- Examples
- Vanilla JavaScript
- AngularJS module
- Helper cheatsheet
- Add the helper in your project
- Regular
<script>tag - With NPM
- Init the helper
- Helper lifecycle
- Objects
- Search
- Events
- Query
- Filtering results
- Facet utilities
- Tags
- Pagination
- Index
- One fourth dimension query
- Query parameters
- Results format
- Browser support
Features
- Search parameters management
- Facets exclusions
- Pagination
- Disjunctive faceting (search on two or more values of the same facet)
Examples
Vanilla JavaScript
A small example that uses Browserify to manage modules.
var algoliasearch = require ( 'algoliasearch' ) ; var algoliasearchHelper = crave ( 'algoliasearch-helper' ) ; var client = algoliasearch ( 'appId' , 'apiKey' ) ; var helper = algoliasearchHelper ( client , 'indexName' , { facets: [ 'mainCharacterFirstName' , 'yr' ] , disjunctiveFacets: [ 'director' ] } ) ; helper . on ( 'result' , office ( issue ) { console . log ( event . results ) ; } ) ; helper . addDisjunctiveFacetRefinement ( 'director' , 'Clint Eastwood' ) ; helper . addDisjunctiveFacetRefinement ( 'managing director' , 'Sofia Coppola' ) ; helper . addNumericRefinement ( 'twelvemonth' , '=' , 2003 ) ; // Search for any movie filmed in 2003 and directed by either C. Eastwood or S. Coppola helper . search ( ) ; See more examples in the examples binder
AngularJS module
< script src = "https://cdn.jsdelivr.net/algoliasearch/iii/algoliasearch.angular.js" > < / script > < script src = "dist/algoliasearch.helper.min.js" > < / script > < script blazon = "text/javascript" > angular.module('searchApp', ['ngSanitize', 'algoliasearch']) .controller('searchController', ['$scope', '$sce', 'algolia', function($scope, $sce, algolia) { var algolia = algolia . Client ( 'applicationId' , 'apiKey' ) ; $scope . q = '' ; $telescopic . content = zilch ; $scope . helper = algoliasearchHelper ( algolia , 'indexName' , { facets: [ 'type' , 'shipping' ] , disjunctiveFacets: [ 'category' , 'manufacturer' ] , hitsPerPage: five , } ) ; $scope . helper . on ( 'outcome' , function ( consequence ) { $telescopic . $use ( office ( ) { $scope . content = event . results ; } ) ; } ) ; $telescopic . toggleRefine = function ( $upshot , facet , value ) { $event . preventDefault ( ) ; $scope . helper . toggleRefine ( facet , value ) . search ( ) ; } ; $scope . $sentry ( 'q' , function ( q ) { $scope . helper . setQuery ( q ) . search ( ) ; } ) ; $scope . helper . search ( ) ; } ] ) ; < /script> You can see the total Angular case here
Helper cheatsheet
At that place is besides a complete JSDoc
Add together the helper in your project
Regular <script> tag
Apply our jsDelivr build:
<script src="https://cdn.jsdelivr.net/algoliasearch.helper/two/algoliasearch.helper.min.js"></script>
With NPM
npm install algoliasearch-helper
Init the helper
var helper = algoliasearchHelper ( client , 'indexName' /*, parameters*/ ) ; Helper lifecycle
-
modify the parameters of the search (ordinarily through user interactions)
helper.setQuery('iphone').addFacetRefinement('category', 'phone') -
trigger the search (later on all the modification have been applied)
helper.search() -
read the results (with the result "result" handler) and update the UI with the results
helper.on('result', function(event) { updateUI(result.results); }); -
go back to one
Objects
AlgoliasearchHelper: the helper. Keeps the state of the search, makes the queries and calls the handlers when an event happen.
SearchParameters: the object representing the state of the search. The current state is stored in helperInstance.state.
SearchResults: the object in which the Algolia answers are transformed into. This object is passed to the result effect handler. An example of SearchResults in JSON is available at the end of this readme
Search
The search is triggered by the search() method.
It takes all the previous modifications to the search and uses them to create the queries to Algolia. The search parameters are immutable.
Example:
var helper = algoliasearchHelper ( customer , indexName ) ; // Permit's monitor the results with the console helper . on ( 'result' , office ( outcome ) { console . log ( result . results ) ; } ) ; // Permit's make an empty search // The results are all sorted using the dashboard configuration helper . search ( ) ; // Let'south search for "landscape" helper . setQuery ( 'mural' ) . search ( ) ; // Let'southward add a category "photograph" // Will make a search with "photograph" tag and "mural" as the query helper . addTag ( 'photograph' ) . search ( ) ; Events
The helper is a Node.js EventEmitter instance.
result: go notified when new results are received. The handler function will receive two objects (SearchResults and SearchParameters).
mistake: get notified when errors are received from the API.
change: get notified when a holding has changed in the helper
search : go notified when a request is sent to Algolia
Listen to the result event
helper . on ( 'result' , updateTheResults ) ; Heed to a event event once
helper . once ( 'event' , updateTheResults ) ; Remove a result listener
helper . removeListener ( 'result' , updateTheResults ) ; Remove all result listeners
helper . removeAllListeners ( 'result' ) ; All the methods from Node.js EventEmitter class are available.
Query
Do a search with the query "fruit"
helper.setQuery('fruit').search(); Filtering results
Facets are filters to retrieve a subset of an alphabetize having a specific value for a given attribute. First you lot demand to define which attribute will exist used every bit a facet in the dashboard: https://www.algolia.com/explorer#?tab=display
Regular (conjunctive) facets
Refinements are ANDed by default (Conjunctive selection).
Facet definition
var helper = algoliasearchHelper ( client , indexName , { facets: [ 'ANDFacet' ] } ) ; Add a facet filter
helper . addFacetRefinement ( 'ANDFacet' , 'valueOfANDFacet' ) . search ( ) ; Remove a facet filter
helper . removeFacetRefinement ( 'ANDFacet' , 'valueOfANDFacet' ) . search ( ) ; Disjunctive facets
Refinements are ORed past default (Disjunctive pick).
Facet definition
var helper = algoliasearchHelper ( customer , indexName , { disjunctiveFacets: [ 'ORFacet' ] } ) ; Add a facet filter
helper . addDisjunctiveFacetRefinement ( 'ORFacet' , 'valueOfORFacet' ) . search ( ) ; Remove a facet filter
helper . removeDisjunctiveFacetRefinement ( 'ORFacet' , 'valueOfORFacet' ) . search ( ) ; Negative facets
Filter so that we do NOT go a given facet
Facet definition (aforementioned as "AND" facet)
var helper = algoliasearchHelper ( customer , indexName , { facets: [ 'ANDFacet' ] } ) . search ( ) ; Exclude a value for a facet
helper . addFacetExclusion ( 'ANDFacet' , 'valueOfANDFacetToExclude' ) ; Remove an exclude from the listing of excluded values
helper . removeFacetExclusion ( 'ANDFacet' , 'valueOfANDFacetToExclude' ) ; Numeric facets
Filter over numeric attributes with math operations like =, >, <, >=, <=. Can exist used for numbers and dates (if converted to timestamp)
Facet definition
var helper = algoliasearchHelper ( customer , indexName , { disjunctiveFacets: [ 'numericAttribute' ] } ) ; Add numeric refinements
helper . addNumericRefinement ( 'numericAttribute' , '=' , 'iii' ) . search ( ) ; // filter to only the results that friction match numericAttribute=3 helper . addNumericRefinement ( 'numericAttribute' , '=' , 'four' ) . search ( ) ; // filter to only the results that lucifer numericAttribute=iii AND numericAttribute=four // On some other numeric with no previous filter helper . addNumericRefinement ( 'numericAttribute2' , '=' , [ '42' , '56' , '37' ] ) . search ( ) ; // filter to only the results that match numericAttribute2=42 OR numericAttribute2=56 OR numericAttribute2=37 Remove a numeric refinement
helper . removeNumericRefinement ( 'numericAttribute' , '=' , '3' ) . search ( ) ; Batch numeric filter removal
// for the unmarried operator = on numericAttribute helper . removeNumericRefinement ( 'numericAttribute' , '=' ) . search ( ) ; // for all the refinements on numericAttribute helper . removeNumericRefinement ( 'numericAttribute' ) . search ( ) ; Hierarchical facets
Hierarchical facets are useful to build such navigation menus:
| products > fruits > citrus | strawberries | peaches | apples Here, we refined the search this mode:
- click on fruits
- click on citrus
Usage
To build such carte, you demand to use hierarchical faceting:
var helper = algoliasearchHelper ( client , indexName , { hierarchicalFacets: [ { proper name: 'products' , attributes: [ 'categories.lvl0' , 'categories.lvl1' ] } ] } ) ; Requirements: All the specified attributes must be defined in your Algolia settings as attributes for faceting.
Given your objects looks similar this:
{ "objectID": "123" , "name": "orange" , "categories": { "lvl0": "fruits" , "lvl1": "fruits > citrus" } } And you refine products:
helper . toggleFacetRefinement ( 'products' , 'fruits > citrus' ) ; You lot will get a hierarchical presentation of your facet values: a navigation carte du jour of your facet values.
helper . on ( 'issue' , role ( event ) { console . log ( event . results . hierarchicalFacets [ 0 ] ) ; // { // 'proper name': 'products', // 'count': null, // 'isRefined': truthful, // 'path': nil, // 'data': [{ // 'proper noun': 'fruits', // 'path': 'fruits', // 'count': one, // 'isRefined': true, // 'information': [{ // 'name': 'citrus', // 'path': 'fruits > citrus', // 'count': 1, // 'isRefined': true, // 'data': zero // }] // }] // } } ) ; To ease navigation, we always:
- provide the root level categories
- provide the current refinement sub categories (
fruits > citrus > *: n + 1) - provide the parent refinement (
fruits > citrus=>fruits: n -one) categories - refine the search using the current hierarchical refinement
Multiple values per level
Your records tin can as well share multiple categories between one another past using arrays within your object:
{ "objectID": "123" , "name": "orange" , "categories": { "lvl0": [ "fruits" , "colour" ], "lvl1": [ "fruits > citrus" , "color > orange" ] } }, { "objectID": "456" , "name": "grapefruit" , "categories": { "lvl0": [ "fruits" , "color" , "new" ], "lvl1": [ "fruits > citrus" , "colour > yellow" , "new > citrus" ] } } Specifying another separator
var helper = algoliasearchHelper ( client , indexName , { hierarchicalFacets: [ { proper noun: 'products' , attributes: [ 'categories.lvl0' , 'categories.lvl1' ] , separator: '|' } ] } ) ; helper . toggleFacetRefinement ( 'products' , 'fruits|citrus' ) ; Would mean that your objects look like so:
{ "objectID": "123" , "name": "orange" , "categories": { "lvl0": "fruits" , "lvl1": "fruits|citrus" } } Specifying a dissimilar sort order for values
The default sort for the hierarchical facet view is: isRefined:desc (first show refined), name:asc (then sort by name).
Yous can specify a different sort order by using:
var helper = algoliasearchHelper ( client , indexName , { hierarchicalFacets: [ { name: 'products' , attributes: [ 'categories.lvl0' , 'categories.lvl1' ] , sortBy: [ 'count:desc' , 'proper noun:asc' ] // showtime testify the near common values, then sort past name } ] } ) ; The bachelor sort tokens are:
- count
- isRefined
- name
- path
Restrict results and hierarchical values to non-root level
Let's say you accept a lot of levels:
- fruits - yellowish - citrus - spicy But you but want to get the values starting at "citrus", you can employ rootPath
You can specify an root path to filter the hierarchical values
var helper = algoliasearchHelper(client, indexName, { hierarchicalFacets: [{ proper name: 'products', attributes: ['categories.lvl0', 'categories.lvl1', 'categories.lvl2', 'categories.lvl3'], rootPath: 'fruits > yellowish > citrus' }] }); Having a rootPath volition refine the results on it automatically.
Hide parent level of current parent level
Past default the hierarchical facet is going to return the child and parent facet values of the current refinement.
If you do not want to get the parent facet values you tin can gear up showParentLevel to false
var helper = algoliasearchHelper ( client , indexName , { hierarchicalFacets: [ { proper name: 'products' , attributes: [ 'categories.lvl0' , 'categories.lvl1' ] , showParentLevel: faux } ] } ) ; Request for the current breadcrumb
var helper = algoliasearchHelper ( client , indexName , { hierarchicalFacets: [ { name: 'products' , attributes: [ 'categories.lvl0' , 'categories.lvl1' ] , separator: '|' } ] } ) ; helper . toggleFacetRefinement ( 'products' , 'fruits|citrus' ) ; var breadcrumb = helper . getHierarchicalFacetBreadcrumb ( 'products' ) ; panel . log ( breadcrumb ) ; // ['fruits', 'citrus'] panel . log ( breadcrumb . join ( ' | ' ) ) ; // 'fruits | citrus' Clearing filters
Clear all the refinements for all the refined attributes
helper . clearRefinements ( ) . search ( ) ; Clear all the refinements for a specific aspect
helper . clearRefinements ( 'ANDFacet' ) . search ( ) ; [ADVANCED] Clear only the exclusions on the "ANDFacet" aspect
helper . clearRefinements ( function ( value , attribute , blazon ) { return type === 'exclude' && attribute === 'ANDFacet' ; } ) . search ( ) ; Facet utilities
Become the values of a facet with the default sort
helper . on ( 'outcome' , function ( effect ) { // Get the facet values for the attribute age event . results . getFacetValues ( 'age' ) ; // It volition exist ordered : // - refined facets kickoff // - then ordered by number of occurence (bigger count -> higher in the list) // - then ordered by proper noun (alphabetically) } ) ; Get the values of a facet with a custom sort
helper . on ( 'result' , function ( event ) { // Become the facet values for the attribute age event . results . getFacetValues ( 'age' , { sortBy: [ 'count:asc' ] } ) ; // Information technology will exist ordered by number of occurence (lower number => higher position) // Elements that can exist sorted : count, name, isRefined // Blazon of sort : 'asc' for ascending club, 'desc' for descending order } ) ; Get the facet stats
This just apply on numeric based facets/attributes.
helper . on ( 'event' , role ( effect ) { // Get the facet values for the attribute age event . results . getFacetStats ( 'age' ) ; } ) ; Tags
Tags are an piece of cake way to practice filtering. They are based on a special aspect in the records named _tags, which can be a single string value or an assortment of strings.
Add a tag filter for the value "landscape"
helper . addTag ( 'landscape' ) . search ( ) ; Remove a tag filter for the value "mural"
helper . removeTag ( 'landscape' ) . search ( ) ; Clear all the tags filters
helper . clearTags ( ) . search ( ) ; Pagination
Get the electric current page
Modify page
helper . setPage ( three ) . search ( ) ; Automatic reset to folio 0
During a search, changing the parameters volition update the result set, which can then change the number of pages in the issue set. Therefore, the behavior has been standardized so that any operation that may modify the number of page volition reset the pagination to page 0.
This may atomic number 82 to some unexpected behavior. For example:
helper . setPage ( four ) ; helper . getPage ( ) ; // 4 helper . setQuery ( 'foo' ) ; helper . getPage ( ) ; // 0 Non exhaustive list of operations that trigger a reset:
- refinements (conjunctive, exclude, disjunctive, hierarchical, numeric)
- tags
- index (setIndex)
- setQuery
- setHitsPerPage
- setTypoTolerance
Index
Index can exist inverse. The common use instance is when you have several slaves with different sort guild (sort by relevance, price or whatsoever other attribute).
Change the current index
helper . setIndex ( 'index_orderByPrice' ) . search ( ) ; Get the current index
var currentIndex = helper . getIndex ( ) ; One time query
Sometime it's convenient to reuse the current search parameters with small changes without changing the country stored in the helper. That'southward why in that location is a function chosen searchOnce. This method does not trigger change or mistake events.
In the following, we are using searchOnce to fetch only a single element using all the other parameters already gear up in the search parameters.
Using searchOnce with a callback
var state = helper . searchOnce ( { hitsPerPage: 1 } , function ( mistake , content , state ) { // if an fault occured it will be passed in mistake, otherwise its value is zippo // content contains the results formatted every bit a SearchResults // state is the instance of SearchParameters used for this search } ) ; Using searchOnce with a hope
var state1 = helper . searchOnce ( { hitsPerPage: i } ) . then ( function ( res ) { // res contains // { // content : SearchResults // land : SearchParameters (the i used for this specific search) // } } ) ; Query parameters
There are lots of other parameters you lot tin gear up.
Set a parameter at the initialization of the helper
var helper = algoliasearchHelper ( client , indexName , { hitsPerPage: fifty } ) ; Set a parameter later
helper . setQueryParameter ( 'hitsPerPage' , 20 ) . search ( ) ; List of parameters that can be set
| Name | Type | Description |
| advancedSyntax | boolean | Enable the advanced syntax. advancedSyntax on Algolia.com |
| allowTyposOnNumericTokens | boolean | Should the engine permit typos on numerics. allowTyposOnNumericTokens on Algolia.com |
| analytics | boolean | Enable the analytics analytics on Algolia.com |
| analyticsTags | string | Tag of the query in the analytics. analyticsTags on Algolia.com |
| aroundLatLng | string | Center of the geo search. aroundLatLng on Algolia.com |
| aroundLatLngViaIP | boolean | Eye of the search, remember from the user IP. aroundLatLngViaIP on Algolia.com |
| aroundPrecision | number | Precision of the geo search. aroundPrecision on Algolia.com |
| aroundRadius | number | Radius of the geo search. aroundRadius on Algolia.com |
| minimumAroundRadius | number | Minimum radius of the geo search. minimumAroundRadius on Algolia.com |
| attributesToHighlight | string | List of attributes to highlight attributesToHighlight on Algolia.com |
| attributesToRetrieve | string | Listing of attributes to remember attributesToRetrieve on Algolia.com |
| attributesToSnippet | string | Listing of attributes to snippet attributesToSnippet on Algolia.com |
| disjunctiveFacets | Array.<string> | All the alleged disjunctive facets |
| distinct | boolean|number | Remove duplicates based on the index setting attributeForDistinct distinct on Algolia.com |
| facets | Assortment.<cord> | All the facets that volition be requested to the server |
| filters | cord | Add filters to the query (similar to WHERE clauses) filters on Algolia.com |
| getRankingInfo | integer | Enable the ranking informations in the response getRankingInfo on Algolia.com |
| hitsPerPage | number | Number of hits to exist returned by the search API hitsPerPage on Algolia.com |
| ignorePlurals | boolean | Should the plurals be ignored ignorePlurals on Algolia.com |
| insideBoundingBox | string | Geo search within a box. insideBoundingBox on Algolia.com |
| insidePolygon | cord | Geo search inside a polygon. insidePolygon on Algolia.com |
| maxValuesPerFacet | number | Number of values for each facetted attribute maxValuesPerFacet on Algolia.com |
| minWordSizefor1Typo | number | Number of characters to wait before doing one grapheme replacement. minWordSizefor1Typo on Algolia.com |
| minWordSizefor2Typos | number | Number of characters to wait before doing a second character replacement. minWordSizefor2Typos on Algolia.com |
| optionalWords | string | Add together some optional words to those defined in the dashboard optionalWords on Algolia.com |
| page | number | The current folio number page on Algolia.com |
| query | cord | Query cord of the instant search. The empty string is a valid query. query on Algolia.com |
| queryType | string | How the query should be treated past the search engine. Possible values: prefixAll, prefixLast, prefixNone queryType on Algolia.com |
| removeWordsIfNoResults | string | Possible values are "lastWords" "firstWords" "allOptional" "none" (default) removeWordsIfNoResults on Algolia.com |
| replaceSynonymsInHighlight | boolean | Should the engine supercede the synonyms in the highlighted results. replaceSynonymsInHighlight on Algolia.com |
| restrictSearchableAttributes | cord | Restrict which attribute is searched. restrictSearchableAttributes on Algolia.com |
| synonyms | boolean | Enable the synonyms synonyms on Algolia.com |
| tagFilters | string | Contains the tag filters in the raw format of the Algolia API. Setting this parameter is non compatible with the of the add/remove/toggle methods of the tag api. tagFilters on Algolia.com |
| typoTolerance | string | How the typo tolerance behave in the search engine. Possible values: true, false, min, strict typoTolerance on Algolia.com |
Results format
Here is an example of a result object you lot get with the result event.
{ "hitsPerPage": ten , "processingTimeMS": two , "facets": [ { "proper name": "type" , "data": { "HardGood": 6627 , "BlackTie": 550 , "Music": 665 , "Software": 131 , "Game": 456 , "Movie": 1571 } , "exhaustive": simulated } , { "exhaustive": false , "data": { "Gratuitous shipping": 5507 } , "name": "aircraft" } ] , "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif" , "_highlightResult": { "shortDescription": { "matchLevel": "none" , "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Cyberspace protection" , "matchedWords": [ ] } , "category": { "matchLevel": "none" , "value": "Computer Security Software" , "matchedWords": [ ] } , "manufacturer": { "matchedWords": [ ] , "value": "Webroot" , "matchLevel": "none" } , "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (one-Year Subscription) - Mac/Windows" , "matchedWords": [ ] , "matchLevel": "none" } } , "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg" , "shipping": "Costless shipping" , "bestSellingRank": four , "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection" , "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ" , "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows" , "category": "Computer Security Software" , "salePrice_range": "1 - l" , "objectID": "1688832" , "type": "Software" , "customerReviewCount": 5980 , "salePrice": 49.99 , "manufacturer": "Webroot" } , .... ] , "nbHits": 10000 , "disjunctiveFacets": [ { "exhaustive": false , "data": { "5": 183 , "12": 112 , "7": 149 , ... } , "name": "customerReviewCount" , "stats": { "max": 7461 , "avg": 157.939 , "min": i } } , { "data": { "Printer Ink": 142 , "Wireless Speakers": 60 , "Point & Shoot Cameras": 48 , ... } , "name": "category" , "exhaustive": simulated } , { "exhaustive": false , "information": { "> 5000": 2 , "i - 50": 6524 , "501 - 2000": 566 , "201 - 500": 1501 , "101 - 200": 1360 , "2001 - 5000": 47 } , "proper noun": "salePrice_range" } , { "data": { "Dynex™": 202 , "Insignia™": 230 , "PNY": 72 , ... } , "name": "manufacturer" , "exhaustive": false } ] , "query": "" , "nbPages": 100 , "folio": 0 , "alphabetize": "bestbuy" } Browser support
This project works on any ES5 browser, basically >= IE9+.
Source: https://www.npmjs.com/package/algoliasearch-helper
0 Response to "Cannot Read Property '_ua' of Undefined Algolia Search"
Post a Comment