EcomSearch

EcomSearch

new EcomSearch(storeIdopt, storageKeyopt, localStorageopt)

Source:
Construct a new search engine instance object.
Examples
const search = new EcomSearch()
// Defining Store ID other than the configured on `$ecomConfig`
const storeId = 2000
const search = new EcomSearch(storeId)
Parameters:
Name Type Attributes Default Description
storeId number <optional>
$ecomConfig.get('store_id') Preset Store ID number
storageKey string | null <optional>
'ecomSeachHistory' Item key to persist search history data
localStorage object <optional>
window.localStorage Local Storage interface

Members

dsl :object

Source:
Current Query DSL for Search API request body.
You can edit this object to manually set Query DSL properties, or you can use instance methods listed below.
Type:
  • object

history :array.<string>

Source:
Search terms history.
Type:
  • array.<string>

localStorage :object

Source:
Type:
  • object

result :result|undefined

Source:
Last search result object obtained with the fetch method.
Type:

storageKey :string|null

Source:
Item key to handle persistent search history data with localStorage.
Type:
  • string | null

storeId :number

Source:
Respective Store ID number.
Type:
  • number

Methods

fetch(isSimpleSearchopt, axiosConfigopt) → {Promise.<(result|error)>}

Source:
Send POST request to E-Com Plus Search API and returns promise resolved with search result.
Example
// Run search request
search.fetch()
  .then(result => {
    console.log(result.took)
    console.log(`${result.hits.total} items found:`)
    console.log(result.hits.hits)
  })
  .catch(error => {
    console.error(error)
    if (error.response) {
      console.log(error.response)
    }
  })
Parameters:
Name Type Attributes Default Description
isSimpleSearch boolean <optional>
false Handle simple (and faster) search without sort and aggregations
axiosConfig object <optional>
Additional axios config object
Returns:
Type
Promise.<(result|error)>

getBrands(resultopt) → {array.<aggregation>}

Source:
List brand options matched from search result object.
Example
// Run search request and list brand aggregations
await search.fetch()
search.getBrands().forEach(aggBrand => {
  console.log(`we have ${aggBrand.doc_count} items with brand ${aggBrand.key}`)
})
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
array.<aggregation>

getCategories(resultopt) → {array.<aggregation>}

Source:
List category options matched from search result object.
Example
// Run search request and list category aggregations
await search.fetch()
search.getCategories().forEach(aggCategory => {
  console.log(`we have ${aggCategory.doc_count} items with category ${aggCategory.key}`)
})
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
array.<aggregation>

getItems(resultopt) → {array.<object>}

Source:
List items from search result object.
Examples
// Run search request and list result items
await search.fetch()
search.getItems().forEach(item => {
  console.log(item)
  console.log(item.name)
})
// You can also pass search result object as param
search.fetch().then(result => search.getItems(result).forEach(({ sku }) => console.log(sku)))
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
array.<object>

getPriceRange(resultopt) → {prices}

Source:
Get minimum, maximum and average item prices from search result object.
Example
// Run search request and get resultant price range
search.fetch().then(() => {
  const { min, avg, max } = search.getPriceRange()
  console.log(`prices => min: ${min}; max: ${max}; avg: ${avg}`)
})
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
prices

getSpecs(resultopt) → {array.<spec>}

Source:
List specification grids and options matched from search result object.
Example
// Run search request and list spec options
await search.fetch()
search.getSpecs().forEach(aggSpec => {
  console.log(`${aggSpec.doc_count} items with grid ${aggSpec.key} and the following options:`)
  aggSpec.options.forEach(aggOption => {
    console.log(`${aggOption.key} (${aggOption.doc_count})`)
  })
})
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
array.<spec>

getTermSuggestions(resultopt) → {array.<suggest>}

Source:
Get list of keyword suggestions based on current search term from result object.
Example
// Run search request with wrong term and get suggestions
search.setSearchTerm('smartprone applo').fetch()
  .then(() => {
    search.getTermSuggestions().forEach(({ text, options }) => {
      const bestOption = options[0]
      // Check match score to suggest term replace
      if (bestOption.score >= 0.83) {
        console.log(`should replace '${text}' by '${bestOption.text}' on search term`)
      }
    })
  })
  .catch(error => {
    console.error(error)
    if (error.response) {
      console.log(error.response)
    }
  })
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
array.<suggest>

getTotalCount(resultopt) → {number}

Source:
Get total number of products found from search result object.
Examples
// Run search request and count total items matched
search.fetch().then(() => console.log(search.getTotalCount()))
// You can also pass search result object as param
try {
  const result = await search.fetch()
  if (search.getTotalCount(result) > 0) {
    // Listing result items as logic example here
    console.log(search.getItems(result))
  }
} catch (error) {
  console.error(error)
}
Parameters:
Name Type Attributes Default Description
result result <optional>
self.result Search result object
Returns:
Type
number

mergeFilter(filter, occuropt) → {self}

Source:
Add/update a filter object on current Query DSL filters list for next search request.
Examples
// Add custom filter by product quantity
search.mergeFilter({
  term: {
    quantity: 0
  }
})
// Set filter by SKUs and run search request
const filter = { terms: { sku: ['nb-apl-1203', 'hd-csr-303'] } }
search.mergeFilter(filter).fetch()
Parameters:
Name Type Attributes Default Description
filter object A valid object for Query DSL filter context
occur string <optional>
'filter' Occurrence type for boolean query
Returns:
Type
self

removeFilter(field, occuropt) → {self}

Source:
Remove a filter object on current Query DSL filters list for next search request.
Examples
// Remove filter by brand IDs and all specification filters
search.removeFilter('brands._id').removeFilter('specs')
// Remove filter by category names and run seach request
search.removeFilter('categories.name').fetch()
Parameters:
Name Type Attributes Default Description
field string A valid item field with dot notation for nested properties
occur string <optional>
'filter' Occurrence type for boolean query
Returns:
Type
self

reset() → {self}

Source:
Reset default Query DSL for Search API request body and unset instance result.
Example
// Reset instance `dsl` and `result`
search.reset()
Returns:
Type
self

setBrandIds(brandIds) → {self}

Source:
Defines list of brand IDs to match on next search request, filtering product results by brand.
Examples
// Set filter by brand ID and run search request
search.setBrandIds([ '5c703b35c626be23430d5030' ]).fetch()
// Remove filter by brand ID
search.setBrandIds(null)
Parameters:
Name Type Description
brandIds array.<string> | null List of brand ObjectIDs (`_id`)
Returns:
Type
self

setBrandNames(brandNames) → {self}

Source:
Defines list of brand names to match on next search request, filtering product results by brand.
Examples
// Set filter by brands and run search request
search.setBrandNames([ 'Corsair', 'Apple' ]).fetch()
// Remove filter by brand names
search.setBrandNames(null)
Parameters:
Name Type Description
brandNames array.<string> | null List of brand names
Returns:
Type
self

setCategoryIds(categoryIds) → {self}

Source:
Defines list of category IDs to match on next search request, filtering product results by category.
Examples
// Set filter by category IDs for next search
search.setCategoryIds([ '5c7009fdc626be23430d4f82', '5c700a53c626be23430d4f88' ])
// Remove filter by category IDs and run search request
search.setCategoryIds(null).fetch()
Parameters:
Name Type Description
categoryIds array.<string> | null List of category ObjectIDs (`_id`)
Returns:
Type
self

setCategoryNames(categoryNames) → {self}

Source:
Defines list of category names to match on next search request, filtering product results by category.
Examples
// Set filter by categories and run search request
search.setCategoryNames([ 'Headset', 'Monitores Gamer' ]).fetch()
// Remove filter by category names
search.setCategoryNames(null)
Parameters:
Name Type Description
categoryNames array.<string> | null List of category names
Returns:
Type
self

setPageNumber(pageopt) → {self}

Source:
Defines next page number for search request (paginate results) starting from 1.
Examples
// Configure to get second page of results and run search request
search.setPageNumber(2).fetch()
// Set back to page number 1
// It's the default preseted page number
search.setPageNumber()
Parameters:
Name Type Attributes Default Description
page number <optional>
1 Integer page number
Returns:
Type
self

setPageSize(limitopt) → {self}

Source:
Defines maximum number of result items for next search request.
Examples
// Set page size 20 and run search request
search.setPageSize(20).fetch()
// Set to 24 the maxium results for next search
// It's the default preseted page size
search.setPageSize()
Parameters:
Name Type Attributes Default Description
limit number <optional>
24 Integer max result size
Returns:
Type
self

setPriceRange(minPrice, maxPrice) → {self}

Source:
Defines range filter to match with product price for next search request.
Examples
// Set filter by price range and run search request
search.setPriceRange(10, 22.5).fetch()
// Remove filter by product price for next search
search.setPriceRange(null, null)
Parameters:
Name Type Description
minPrice number | null Minimun price value
maxPrice number | null Maximun price value
Returns:
Type
self

setProductIds(productIds) → {self}

Source:
Defines list of product IDs to match on next search request.
Examples
// Set filter by ID and run search request
search.setProductIds([ '5c703c40c626be23430d5033' ]).fetch()
// Remove filter by product ID
search.setProductIds(null)
Parameters:
Name Type Description
productIds array.<string> | null List of product ObjectIDs (`_id`)
Returns:
Type
self

setSearchTerm(term) → {self}

Source:
Defines term to match with product name and/or keywords on next search request.
Examples
// Set new search term
search.setSearchTerm('smartphone')
// Set new term and run search request
search.setSearchTerm('notebook').fetch()
Parameters:
Name Type Description
term string Term to be searched
Returns:
Type
self

setSkus(skus) → {self}

Source:
Defines list of product SKUs to match on next search request.
Examples
// Set filter by SKUs for next search
search.setSkus(['nb-apl-1203', 'hd-csr-303'])
// Remove filter by SKU and run search request
search.setSkus(null).fetch()
Parameters:
Name Type Description
skus array.<string> | null List of product SKUs
Returns:
Type
self

setSortOrder(enumOrderopt) → {self}

Source:
Defines most common sorting options and set on instance query for next search request.
Examples
// Set sort by top selling products and run search request
search.setSortOrder('sales').fetch()
// Sort next search result starting by most popular products
// It's the default preseted sort order (views)
search.setSortOrder()
Parameters:
Name Type Attributes Default Description
enumOrder 'sales' | 'news' | 'lowest_price' | 'highest_price' | 'offers' | 'slug' | 'sku' | 'views' <optional>
'views' Sort option enum or valid asc sortable item field
Returns:
Type
self

setSpec(gridId, textOptions) → {self}

Source:
Add, update or remove search filter by product specification based on grid ID and list of text options to match.
Examples
// Set filter by size specification and run search request
search.setSpec('size', ['M', 'G']).fetch()
// Update size options and search again
search.setSpec('size', ['P', 'M', 'G']).fetch()
// Remove filter by size for next search
search.setSpec('size', null)
Parameters:
Name Type Description
gridId string Grid ID such as 'size'
textOptions array | null List of chosen options such as `['M', 'G']` or null to clear current grid filter
Returns:
Type
self