谷歌自定义搜索-查询数据库/API


Google Custom Search - Query database/API?

我们对在我们的项目中使用谷歌自定义搜索/谷歌很感兴趣,主要是因为它在共轭&纠正拼写错误的单词。

我们知道它可以返回JSON或XML格式的数据,我们对此很满意。但找到问题的答案:

我们可以使用这种共轭和纠错并搜索我们自己的数据库/api吗

如果您键入drnks with no alcohol,它会自动更正为drinks with no alcohol,然后像这样搜索我们的数据库:

http://example.com?search=drinks&酒精=0,它可能会做出这样的反应:

{
    "coke": {
        "alcohol": 0,
        "calories": 300,
        "taste": "awesome"
    },
    "pepsi": {
        "alcohol": 0,
        "calories": 300,
        "taste": "meh"
    }
}

然后它会以某种形式返回这两个结果

使用付费版本的解决方案很好。

如果可以这样做,你能给我举一个简单的例子吗?

Google为他们的自定义搜索提供了一个REST API,您可以从服务器上查询它,以确定搜索词是否有更好的拼写,然后使用它来查询您的内部数据库。

在我的代码中,我使用了Guzzle,这是一个REST客户端库,可以避免cURL丑陋而冗长的代码,但如果你真的需要,可以随意使用cURL。

// Composer's autoloader to load the REST client library
require "vendor/autoload.php";
$api_key = "..."; // Google API key, looks like random text
$search_engine = "..."; // search engine ID, looks like "<numbers>:<text>"
$query = "drnks with no alcohol"; // the original search query
// REST client object with some defaults
// avoids specifying them each time we make a request
$client = new GuzzleHttp'Client(["base_url" => "https://www.googleapis.com", "defaults" => ["query" => ["key" => $api_key, "cx" => $search_engine, "fields" => "spelling(correctedQuery)"]]]);
try {
    // the actual request, with the search query
    $resp = $client->get("/customsearch/v1", ["query" => ["q" => $query]])->json();
    // whether Google suggests an alternative spelling
    if (isset($resp["spelling"]["correctedQuery"])) {
        $correctedQuery = $resp["spelling"]["correctedQuery"];
        // now use that corrected spelling to query your internal DB
        // or do anything else really, the query is yours now
        echo $correctedQuery;
    } else {
        // Google doesn't have any corrections, use the original query then
        echo "No corrections found";
    }
} catch (GuzzleHttp'Exception'TransferException $e) {
    // Something bad happened, log the exception but act as if
    // nothing is wrong and process the user's original query
    echo "Something bad happened";
}

以下是获取API密钥的一些说明,可以从控制面板获取自定义搜索引擎ID。

如果你仔细查看,你会发现我已经指定了fields查询参数来请求只包含最终拼写建议的部分响应,以(希望)获得更好的性能,因为我们不需要响应中的任何其他内容(但如果你确实需要完整的响应,请随时更改/删除它)。

请注意,谷歌对你的数据库中的内容一无所知,因此拼写更正将仅基于谷歌对你网站的公开数据,我认为没有办法让谷歌了解你的内部数据库,也不是说这是个好主意。

最后,确保通过仍然为用户提供使用原始查询进行搜索的可能性来优雅地处理速率限制和API故障(就像没有发生任何错误一样,只记录错误以供稍后查看)。