【发布时间】:2020-01-17 18:26:32
【问题描述】:
我有一个使用 Algolia 的 React InstantSearch 的网页。它有一个搜索栏和一些改进。
我希望用户能够按下按钮并获得所有个匹配结果的列表。
要获得所有结果的列表,我需要使用Browse Index 而不是Search Index。浏览索引允许检索所有命中;搜索索引最多只能检索 1000 个匹配项。但是,不应在 UI 中使用浏览索引。因此,我想在我的 Web 服务器上创建一个 API 端点,该端点使用浏览索引来返回给定搜索查询的匹配命中列表。
我能够成功地为搜索查询执行此操作,但我不知道如何进行优化。
这是我目前所拥有的草图。
后端(在 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>
);
}
我找不到任何资源来解释如何使用优化进行搜索。
到目前为止我看过的东西:
我可以尝试将searchState format 映射到浏览索引使用的Search API Parameters。我可以编写自己的从搜索状态到查询的映射器,但是,1)这看起来很复杂,我怀疑我错过了一些更简单的东西,2)这似乎应该在某个地方开源,因为我怀疑我不是首先遇到这个问题。
有一篇文章,Backend InstantSearch ,解释了如何编写一个可以插入到
InstatSearch组件中的后端。但是它没有解释我如何从搜索状态进行一次性搜索。
【问题讨论】:
标签: algolia