如果查询为空,如何将 Algolia 设置为不 return 任何结果?

How do I set Algolia to not return any results if the query is blank?

我正在使用 Algolia 提供的 instantsearch.js 库。

我想要的行为是:如果访问者没有在搜索框中输入任何内容,则不会返回任何结果。

但是,Algolia documentation 指出:

If no query parameter is set, the textual search will match with all the objects.

是否可以更改此行为,同时仍使用 instantsearch.js?

这是我目前拥有的代码:

<script type="text/javascript" src="http://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
<script type="text/javascript">

    window.onload = function ()
    {

        function getTemplate(templateName) {
            return document.getElementById(templateName + '-template').innerHTML;
        }

        var search = instantsearch({
            appId: '{{config["ALGOLIA_APPLICATION_ID"]}}',
            apiKey: '{{config["ALGOLIA_API_KEY"]}}',
            indexName: '{{config["ALGOLIA_INDEX_NAME"]}}',
            urlSync: true
        });

        search.addWidget(
            instantsearch.widgets.searchBox({
                container: '#search-input'
            })
        );

        search.addWidget(
            instantsearch.widgets.hits({
                container: '#hits-container',
                hitsPerPage: 10,
                templates: {
                    item: getTemplate('hit'),
                    empty: getTemplate('no-results')
                }
            })
        );

        search.start();
    };

</script>

您可以使用 searchFunction 并检查底层助手 state 来检查查询是否为空。基于此,您可以 show/hide 搜索结果 div。

var search = instantsearch({
  [...],
  searchFunction: function(helper) {
    var homePage = $('.home-page');
    var searchResults = $('.search-results');
    if (helper.state.query === '') {
      // empty query string -> hide the search results & abort the search
      searchResults.hide();
      homePage.show();
      return;
    }
    // perform the regular search & display the search results
    helper.search();
    homePage.hide();
    searchResults.show();
  }
}

这也是官网documented

@aseure 的解决方案将导致脚本 return 在输入中单击 "x" 以清除搜索查询。以下内容在不破坏任何东西的情况下实现了目标:

const search = instantsearch({
  /* other parameters */
  searchFunction(helper) {
    const container = document.querySelector('#results');

    if (helper.state.query === '') {
      container.style.display = 'none';
    } else {
      container.style.display = '';
    }

    helper.search();
  }
});

以上示例取自此处的文档: https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/js/#handling-empty-queries