Filter search by initial text query instantsearch.js

Is there a way to always apply an initial text query to a search, perhaps using the filters?

For example, let’s say you are searching some data like this:

{
   Url: "http://www.example.com/"
},
{
   Url: "http://www.example.com/sub-folder/"
}
,
{
   Url: "http://www.example.com/sub-folder-two/one"
}
,
{
   Url: "http://www.example.com/sub-folder-two/two"
}

And when you search, you want to filter your search initially for “/sub-folder-two/” so that returned results are limited to data with that starting string.

One way I thought was using the searchFunction:

instantsearch({
...
    searchFunction: function (helper) {
        helper.state.query += " /sub-folder-two/";
        helper.search();
    }
});

What are the different ways you could do this with instantsearch.js or the helper.js?

Hi @mattucci,

One way to do this is to modify the shape of your records. You can update them in order to have the folder as an attribute. With this kind of structure you will be able to apply filters on your records.

{
   url: "http://www.example.com/",
   folder: "",
},
{
   url: "http://www.example.com/sub-folder/",
   folder: "sub-folder",
},
{
   url: "http://www.example.com/sub-folder-two/one",
   folder: "sub-folder-two",
}
{
   filters: 'folder:sub-folder-two',
}

Hope that helps, let me know if you have questions :wink:

1 Like

Thanks Samuel :slight_smile:
That is definitely a good option!

Outside of modifying the data structure, is there anything else I could try?
I guess Algolia doesn’t have anything that achieves a “search within a search”?

Hi @mattucci,

Without modifying the data structure, your solution is totally fine! But you should avoid to mutate the helper state directly, use the setQuery method instead.

instantsearch({
  searchFunction: function(helper) {
    const currentQuery = helper.getQueryParameter("query");

    helper
      .setQuery(currentQuery + " /sub-folder-two/")
      .search();
  }
});

Hope that helps!

1 Like

Thanks for tip in avoiding mutating the helper state! :smile:

I was thinking about a solution for adding multiple levels of a url to the index and I thought of a structure like this:

{
    url: "http://www.example.com/level1/level2/level3",
    folders: [
        {
            name: "level1"
            level: 1
        },
        {
            name: "level1/level2"
            level: 2
        },
        {
            name: "level1/level2/level3"
            level: 3
        }
    ]
}

Does this make sense? See anything wrong with it?