Google 搜索自动完成/自动建议功能缓慢

时间:2021-01-12 20:08:09

标签: php google-api google-custom-search autosuggest google-suggest

我对基于 Google CSE 的搜索引擎的自动完成响应有疑问。 它从第三个字母开始自动完成,加载列表至少需要 2-3 秒。 其他自定义搜索脚本并非如此。

网站:https://searchpal.com

请指教,是否有以下代码或建议查询 URL 导致了这种缓慢?

谢谢大家

代码如下

/**
 * Suggests queries as the user types from Google auto-complete
 *
 * @return
 */
public function suggestQueries()
{
    $app = app();
    $q = $app->request->get('q');

    // Handle aborted connections
    // hopefully
    if (connection_aborted()) {
        return json([$q]);
    }

    if (empty($q)) {
        return json([$q]);
    }

    $locale = get_theme_active_locale();

    $url = "https://suggestqueries.google.com/complete/search?client=firefox&q={$q}&hl=$locale";
    $http = Http::getSession();
    try {
        $response = $http->get($url);
    } catch (\Exception $e) {
        // ssh!
        return json([$q]);
    }

    if (!$response->success) {
        return json([$q]);
    }

    $json = json_decode($response->body, true);

    if (empty($json[1])) {
        return json([$q]);
    }

    $data = [];
    //unset($json[1][0]);

    foreach ($json[1] as $value) {
        $data[] = $value;
    }

    return json($data);

0 个答案:

没有答案