Search by Algolia
What is online retail merchandising? An introduction
e-commerce

What is online retail merchandising? An introduction

Done any shopping on an ecommerce website lately? If so, you know a smooth online shopper experience is not optional ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

5 considerations for Black Friday 2023 readiness
e-commerce

5 considerations for Black Friday 2023 readiness

It’s hard to imagine having to think about Black Friday less than 4 months out from the previous one ...

Piyush Patel

Chief Strategic Business Development Officer

How to increase your sales and ROI with optimized ecommerce merchandising
e-commerce

How to increase your sales and ROI with optimized ecommerce merchandising

What happens if an online shopper arrives on your ecommerce site and: Your navigation provides no obvious or helpful direction ...

Catherine Dee

Search and Discovery writer

Mobile search UX best practices, part 3: Optimizing display of search results
ux

Mobile search UX best practices, part 3: Optimizing display of search results

In part 1 of this blog-post series, we looked at app interface design obstacles in the mobile search experience ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Mobile search UX best practices, part 2: Streamlining search functionality
ux

Mobile search UX best practices, part 2: Streamlining search functionality

In part 1 of this series on mobile UX design, we talked about how designing a successful search user experience ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Mobile search UX best practices, part 1: Understanding the challenges
ux

Mobile search UX best practices, part 1: Understanding the challenges

Welcome to our three-part series on creating winning search UX design for your mobile app! This post identifies developer ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Teaching English with Zapier and Algolia
engineering

Teaching English with Zapier and Algolia

National No Code Day falls on March 11th in the United States to encourage more people to build things online ...

Alita Leite da Silva

How AI search enables ecommerce companies to boost revenue and cut costs
ai

How AI search enables ecommerce companies to boost revenue and cut costs

Consulting powerhouse McKinsey is bullish on AI. Their forecasting estimates that AI could add around 16 percent to global GDP ...

Michelle Adams

Chief Revenue Officer at Algolia

What is digital product merchandising?
e-commerce

What is digital product merchandising?

How do you sell a product when your customers can’t assess it in person: pick it up, feel what ...

Catherine Dee

Search and Discovery writer

Scaling marketplace search with AI
ai

Scaling marketplace search with AI

It is clear that for online businesses and especially for Marketplaces, content discovery can be especially challenging due to the ...

Bharat Guruprakash

Chief Product Officer

The changing face of digital merchandising
e-commerce

The changing face of digital merchandising

This 2-part feature dives into the transformational journey made by digital merchandising to drive positive ecommerce experiences. Part 1 ...

Reshma Iyer

Director of Product Marketing, Ecommerce

What’s a convolutional neural network and how is it used for image recognition in search?
ai

What’s a convolutional neural network and how is it used for image recognition in search?

A social media user is shown snapshots of people he may know based on face-recognition technology and asked if ...

Catherine Dee

Search and Discovery writer

What’s organizational knowledge and how can you make it accessible to the right people?
product

What’s organizational knowledge and how can you make it accessible to the right people?

How’s your company’s organizational knowledge holding up? In other words, if an employee were to leave, would they ...

Catherine Dee

Search and Discovery writer

Adding trending recommendations to your existing e-commerce store
engineering

Adding trending recommendations to your existing e-commerce store

Recommendations can make or break an online shopping experience. In a world full of endless choices and infinite scrolling, recommendations ...

Ashley Huynh

Ecommerce trends for 2023: Personalization
e-commerce

Ecommerce trends for 2023: Personalization

Algolia sponsored the 2023 Ecommerce Site Search Trends report which was produced and written by Coleman Parkes Research. The report ...

Piyush Patel

Chief Strategic Business Development Officer

10 ways to know it’s fake AI search
ai

10 ways to know it’s fake AI search

You think your search engine really is powered by AI? Well maybe it is… or maybe not.  Here’s a ...

Michelle Adams

Chief Revenue Officer at Algolia

Cosine similarity: what is it and how does it enable effective (and profitable) recommendations?
ai

Cosine similarity: what is it and how does it enable effective (and profitable) recommendations?

You looked at this scarf twice; need matching mittens? How about an expensive down vest? You watched this goofy flick ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What is cognitive search, and what could it mean for your business?
ai

What is cognitive search, and what could it mean for your business?

“I can’t find it.”  Sadly, this conclusion is often still part of the modern enterprise search experience. But ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Looking for something?

Build a store locator that includes online sellers
facebookfacebooklinkedinlinkedintwittertwittermailmail

Let’s say you’ve been tasked to build an application to help consumers find agencies providing a specific service. Some of these agencies are local brick-and-mortar storefronts and others are online-only agencies that service the same local area.

This problem was initially posed by Alejo Arias in the Algolia forum:

I have a series of providers in my index:

  • some are national providers (they have a national: true attribute)
  • some are state-wide providers (they have a state attribute with the list of states they service, e.g. [“NY”, “FL”])
  • some are local (they have specific lat/lng in their _geoloc attribute)

I want in my results anything that matches local providers by location close to my users, but also provide (in the same results) state and national providers.

Adding a aroundLatLng filter automatically removes other results, no matter what facets or filters I try.

How can I achieve this?
Basically I want to have something like: aroundLatLng: x,y OR state: NY OR national: true

So how do you combine results from a geographic search for brick-and-mortar stores and with other results from boolean or text-based queries? And how do you build an interface to display them in a unified way?

Geographic data and Algolia Search

As Alejo mentions, you can use Algolia for geographic searches by adding a special _geoloc attribute on your records. You put one or more sets of latitude/longitude tuples into this attribute to indicate geographic locations linked to the record.

Then you use the Algolia client libraries to query against these geocoded records — filtering either within a radius around a fixed point (aroundLatLong) or the area within a shape (insideBoundingBox or insidePolygon). The documentation goes into more detail about the differences between these methods. You can also read through these posts that walk you through building a pure-geographic store locator.

However, you cannot extract geographic and non-geographic results from the same query. If you are searching for proximity, records lacking _geoloc attributes will not show up in the result set.

So how do you perform this search when not all records have geographic coordinates?

A single index solution

You could do the whole thing via geographic search. By adding _geoloc data to the state and national records, you could search for everything using a geographic query. For instance, placing the statewide agencies at coordinates at the center of each state. This was the initial solution I added to the forum post, but there are several problems with this solution:

  1. Alejo specifically mentions that some providers span multiple states
  2. Placing providers at the center of the state will cause inaccurate results for consumers who live near state borders
  3. National providers would need records in every state

A multi-index solution

As an alternative you can build a multi-index solution with one index for the brick-and-mortar storefronts that include geographic data, and another for the state and national providers. You can then search the two data sources independently and blend the result sets. This approach requires two Algolia queries per search, but it will allow us to guarantee results from both types of providers.

Preparing your indices

First, you’ll need an agency data set. You can build one from scratch using a couple of sources. You can start with anonymized address data from this repo containing about 3000 addresses across the United State. Then, run these addresses through a small script to add fictional agency names and randomly flag some of the agencies as “preferred”.

def transform_records(addresses):
  address_records = []
  for address in addresses:
    record = {}
    record_geocode = {}
    # One in ten chance agency is preferred 
    record['preferred'] = 10 == random.randint(1,10)

    record['objectID'] = random_name.generate_name().title()
    if record['preferred']:
      record['name'] = f"{record['objectID']} Agency (Preferred)"
    else:
      record['name'] = f"{record['objectID']} Agency"
    record['address'] = address.get('address1')
    record['city'] = address.get('city')
    record['state'] = address.get('state')
    record['zip'] = address.get('postalCode')
    record_geocode['lat'] = address['coordinates']['lat']
    record_geocode['lng'] = address['coordinates']['lng']
    record['_geoloc'] = record_geocode
    address_records.append(record)
  return address_records

You can use another script to generate statewide and multi-state agencies for the second index. Both data sets reside in this repo. You can create indices from these data sets under your existing Algolia account or sign up for a free account and set up a new agency_finder application.

Building the front end

Now that you’ve populated your indices, it’s time to build the front end. Algolia’s geoSearch component in the InstantSearch library includes a helper component to initialize the Google Maps API, render a Map, and tie that map to geolocation queries in your Algolia index. It’s the same component I used previously to build a COVID-19 case visualizer. However, for this project, you want the user to type in an address and resolve the geolocation information for them using the Google Places API. This proves challenging using the out-of-the-box components in InstantSearch, so you’ll build your own interface from scratch.

This blog post gives us a solid model for building an address autocomplete form in React. You’ll use this as the foundation for your AgencyFinderForm component to render the address autocomplete input field as well as read-only fields to display the resulting address. The latitude/longitude are stored in state, but not shown on the form

You can modernize the code from the blog by using the Google Wrapper around your React components to initialize the google object and add the Places API.

   renderForm = (status) => {
    switch (status) {
      case Status.SUCCESS:
        return ;
      default:
        return <h3>{status} ...</h3>;
      };
  }

  render() {
    return (
      <div>
        <h1>Find an Agency</h1>
        <p className='instructions'>🔍 Search for your address to find the closest agencies.</p>
        <div className='left-panel'>
          <Wrapper apiKey={process.env.REACT_APP_GOOGLE_API_KEY} render={this.renderForm} libraries={["places"]} />
        </div>
        <div className='right-panel'>
          <AgencyFinderResults hits={this.state.results} />
        </div>
      </div>
    )
  }
}

Next you add a clear button to the basic form.

  handleClear() {
    this.setState(this.initialState);
    var input = document.getElementById('autocomplete');
    input.value = '';
    google.maps.event.removeListener(this.autocompleteListener);
    this.initAutocomplete();
  }

Finally, you’ll clean up processing the address_components from the Places API with following code:

  handlePlaceSelect() {
    const addressObject = this.autocomplete.getPlace();
    const address = addressObject.address_components.reduce((seed, { short_name, types }) => {
      types.forEach(t => {
        seed[t] = short_name;
      });
      return seed;
    }, {});
    [this setState](this.setState)({
      streetAddress: `${address.street_number} ${address.route}`,
      city: address.locality ? address.locality : address.sublocality_level_1,
      state: address.administrative_area_level_1,
      zipCode: address.postal_code,
      geoCode: addressObject.geometry.location.lat() + ', ' + addressObject.geometry.location.lng(),
    });
  }

Querying for results

After the user has selected a location and you have the latitude, longitude, and address information stored in the component state, you’re ready to query the indices. You use the multipleQueries method from the Javascript API client to batch together the two queries and combine the results. This will still count as two queries against your Algolia limit, but it reduces the number of round trips to the API.

handleSubmit(event) {
    const queries = [{
      indexName: statesIndex,
      query: this.state.state,
      params: {
        hitsPerPage: 10
      }
    }, {
      indexName: geoIndex,
      query: '',
      params: {
        aroundLatLng: this.state.geoCode,
        facetFilters: [ this.state.preferred ? 'preferred:true' : '' ],
        hitsPerPage: 10,
      }
    }];
    
    this.searchClient.multipleQueries(queries).then(({ results }) => {
      let allHits = [];
      results.map((result) => {
        return allHits.push(...result.hits);
      });
      this.props.handleCallback(allHits);
    });
  }

First, you initialize the two queries. Notice how the multipleQueries method allows us to mix geographic and string-based queries, and even layer in an
optional facetFilter for your “Preferred” agencies. You then pass the array of queries to the client. The response includes the individual results from each
query, but you can just smash the hits from the two result sets into a single array and pass them to the AgencyFinderResults component.

Putting it all together

You now have a solid proof-of-concept React component for layering geographic and non-geographic results into a single result set. At this point you could improve the example by adding a Google Map to display the geographic results. You could also pivot back to a single index, using multipleQueries ability to query the same index multiple times with different parameters.

The complete example is available in this Github repo or you can try out a live demo.

About the author
Chuck Meyer

Sr. Developer Relations Engineer

githubtwitter

Recommended Articles

Powered byAlgolia Algolia Recommend

Building a Store Locator in React using Algolia, Mapbox, and Twilio – Part 3
engineering

Clément Sauvage

Software Engineer, Freelance

Building a Store Locator in React using Algolia, Mapbox, and Twilio – Part 2
engineering

Clément Sauvage

Software Engineer, Freelance

Replicating the Algolia documentation search with Autocomplete
ux

Sarah Dayan
François Chalifour

Sarah Dayan &

François Chalifour