Algolia:如何将改进从前端传递到后端?

Algolia: How to pass refinements from a front-end to a backend?

我有一个使用 Algolia 的 React InstantSearch 的网页。它有一个搜索栏和一些改进。

我希望用户能够按下按钮并获得 所有 匹配结果的列表。

要获得 所有 个结果的列表,我需要使用 Browse Index instead of the Search Index。浏览索引允许检索所有命中;搜索索引最多只能检索 1000 个匹配项。但是,不应在 UI 中使用浏览索引。所以我想创建一个 API 我的网络服务器端点,它使用浏览索引,以便 return 给定搜索查询的匹配列表。

我能够成功地为搜索查询执行此操作,但我不知道如何进行优化。

这是我目前的草图。

后端(在Ruby):

ALGOLIA_INDEX = Algolia::Index.new('Products')

class AlgoliaSearchController < ActionController::Base
  def get_search_results
    query = params['query']
    hits = []
    ALGOLIA_INDEX.browse({query: query}) do |hit|
      hits << hit
    end
    render json: hits
  end
end

前端:

import qs from 'qs';
import React, { useCallback, useState } from 'react';
import { InstantSearch } from 'react-instantsearch-dom';

function getSearchResults(query) {
  const queryString = qs.stringify({
    query,
  })
  return fetch(`/search_results?{queryString}`);
}


function App() {
  const [searchState, setSearchState] = useState(null);
  const onSearchStateChange = useCallback(searchState => {
    setSearchState(searchState);
  }, [searchState]);
  const onClick = useCallback(() => {
    console.log(getSearchResults(searchstate.query));
  });

  return (
    <InstantSearch ... onSearchStateChange={onSearchStateChange}>
      <button onClick={onClick}>Search</button>
    </InstantSearch>
  );
}

我找不到任何资源来解释如何使用优化进行搜索。

到目前为止我看过的东西:

你是对的,目前这不是很简单。获取可用于 "browse" 的原始搜索参数的流程如下所示:

  1. 让您的自定义组件访问最后的搜索结果
  2. 从这些结果中读取状态
  3. 使用此状态创建一个新的helper
  4. 使用helper.getQuery()获取要应用的查询参数

说明这一点的沙箱是:https://codesandbox.io/s/extending-widgets-luqd9

import React, { Component } from 'react';
import algoliaHelper from 'algoliasearch-helper';
import { connectStateResults } from 'react-instantsearch-dom';

class Downloader extends Component {
  state = {
    instructions: '',
  };

  onDownloadClick = () => {
    // get the current results from "connectStateResults"
    const res = this.props.searchResults;
    // read the private "state" (SearchParameters) from the last results
    const state = res && res._state;
    // create a new "helper" with this state
    const helper = algoliaHelper({}, state.index, state);
    // get the query parameters to apply
    const rawQuery = helper.getQuery();
    this.setState({
      instructions:
        'Do a search backend with this:\n\nclient.browseAll(' +
        JSON.stringify(rawQuery, null, 2) +
        ')',
    });
  };

  render() {
    return (
      <React.Fragment>
        <button onClick={this.onDownloadClick}>download</button>
        <pre>{this.state.instructions}</pre>
      </React.Fragment>
    );
  }
}

export default connectStateResults(Downloader)