使用 Google 本书 API 的推荐结果不相关

Results of recommendations using Google Books API are irrelevant

我正在尝试使用 Google 本书 API 构建书名推荐系统。 不幸的是,与 https://books.google.com 相比,我得到的结果非常不相关。例如,这是我通过单词 "sher" 搜索得到的列表(主要期待像 Sherlock Holmes 这样的东西)。

`She Said Yes;The Oh She Glows Cookbook;What Can She Know?;She-Wolf;Murder She Wrote;My Mother She Killed Me, My Father He Ate Me;22 Things a Woman Must Know If She Loves a Man with Asperger's Syndrome;Where She Danced;The Israeli-Palestinian Peace Negotiations, 1999-2001`

如您所见,甚至没有最相关的标题。如果您在 google 图书网站上键入 "Sher",您将获得绝对正确的相关推荐。我理解 Google API 对吗?我的代码有什么问题?

            var request = 'https://www.googleapis.com/books/v1/volumes';
            var outputbookslistshow = 0; 
            $('#myTextArea').on('keyup', function(){
                if(outputbookslistshow == 0){
                  outputbookslistshow = 1;
                  $('#outputgbooksrec').show(300); // it's a div for outputting titles
                }
            $('#outputgbooksrec').empty();
                 var keywords = $(this).val();
                if(keywords.length > 0 ){
                      $.getJSON(request + '?q=' + keywords, function(response){
                        for (var i = 0; i < response.items.length; i++) {
                    var item = response.items[i];
             document.getElementById("outputgbooksrec").innerHTML += "<br>"
 + "<div class='itembook'>" + item.volumeInfo.title + "</div>";
        } 
        })
        }

    });

0。 TLDR

这是一个working fiddle using Google's https://suggestqueries.google.com/complete/search

参数:

output/client  # "toolbar" => xml, "firefox" => json, "chrome" => jsonp
ds             #  which site to search in ("bo" for books, "yt" for youtube...)
q              #  search term: "sher"

查询:

https://suggestqueries.google.com/complete/search?output=firefox&ds=bo&q=sher

结果:

["sher",["sherlock holmes","sherrilyn kenyon","sherman alexie","sheryl sandberg","sherlock","sherlock holmes short stories","sherlock holmes book","sher o shayari","sherlock holmes novels","sher shah suri"]]

1。建议与搜索结果

首先要意识到,当 Google 提出建议时,它们并不是您按回车键时显示的结果。

如果您的查询中包含相关术语,

搜索结果 是相关的。

建议假设您的查询不完整,因此将您的查询与其他查询进行比较,以猜测您的查询的完整版本可能是什么。

当我在 http://books.google.com 上搜索 "sher" 时,我看到的结果是:

  • 以色列-巴勒斯坦和平谈判,1999-2001
  • 超越中立:完美主义与政治
  • 沙漠
  • 拒绝选择!:利用你所有的兴趣、激情……

原因是作者:在前三个的情况下,"George Sher"和在第四个的情况下"Barbara Sher"。这是理想的行为,因为当我搜索 "sher" 时,我不希望 "Sherlock" 结果掩埋 "George Sher".


2。解决方案

Google 也有一种 API 的建议。关于它的一些信息 can be found here。更重要的是,使用开发人员工具,您可以准确地看到 Google 在做什么。

使用开发者工具:检查https://books.google.com页面(CTRL+SHIFT+i 在 Chrome)。转到网络选项卡并等待所有内容加载完毕。

当您开始输入时,Google 会向服务器发出请求,您会在列表中看到这些请求。当我输入 "sher" 时,Google 发送了这个请求:

https://suggestqueries.google.com/complete/search?client=books&ds=bo&q=sher&callback=_callbacks_._1id33zyi5

查看变量:

client   = books
ds       = bo
q        = sher
callback = _callbacks_._1id33zyi5
  • client 确定您收到的结果类型(XML [toolbar], JSON [firefox], JSONP [ chrome])
  • ds 将搜索限制在特定站点(图书 [bo]、youtube [yt] 等)。
  • q 当然是查询文本
  • callback 是用于 JSONP 的参数(其中有一些 important differences to JSON)。不用太担心,因为 jQuery 可以为您处理。

我通过查看此请求和阅读 this and this.

拼凑了有关这些参数的一些信息

CORS: 因为您从 google.com 以外的域发出请求,您将收到 Access-Control-Allow-Origin 错误。这是一项试图防止 XSS 的安全措施。要解决此问题,您需要使用 JSONP.

使用 jQuery,我们不必担心回调,所以让我们将客户端参数更改为 chrome 并使用此最终查询:

https://suggestqueries.google.com/complete/search?client=chrome&ds=bo&q=sher

Working Example Below: In this example, you may want to take note of the "google:suggestrelevance" key which is an added bonus of using JSONP (Google only returns that information in JSONP data).

var requestUrl = "https://suggestqueries.google.com/complete/search?client=chrome&ds=bo&q=";
var xhr;

$(document).on("input", "#query", function () {
    typewatch(function () {
        // Here's the bit that matters
        var queryTerm = $("#query").val();
        $("#indicator").show();
        if (xhr != null) xhr.abort();
        xhr = $.ajax({
            url: requestUrl + queryTerm,
            dataType: "jsonp",
            success: function (response) {
                $("#indicator").hide();
                $("#response").html(syntaxHighlight(response));
            }
        });
    }, 500);
});


/*
 *  --------- YOU ONLY NEED WHAT IS ABOVE THIS LINE ---------
 */
$(document).ready(function () {
    $("#indicator").hide();
});

// Just for fun, some syntax highlighting...
// Credit: 
function syntaxHighlight(json) {
    if (typeof json != 'string') {
        json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

// And automatic searching (when you stop typing)
// Credit: 
var typewatch = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();
/* 
 * Safe to ignore:
 * This is just to make stuff look vaguely decent
 */
body {
  padding: 10px;
}
div * {
    vertical-align: top;
}
#indicator {
    display: inline-block;
    background: no-repeat center/100% url('http://galafrica.actstudio.ro/img/busy_indicator.gif');
    width: 17px;
    height: 17px;
    margin: 3px;
}
/*
 *
 * CREDIT:
 * 
 */
 pre {
    outline: 1px solid #ccc;
    padding: 5px;
}
.string {
    color: green;
}
.number {
    color: darkorange;
}
.boolean {
    color: blue;
}
.null {
    color: red;
}
.key {
    color: #008;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <input type=text id="query" placeholder="Start typing..." /><span id="indicator"></span>

</div>
<pre id="response"></pre>