使用Google Books API的建议结果无关紧要 [英] Results of recommendations using Google Books API are irrelevant
问题描述
我正在尝试使用Google Books API建立书名推荐系统。
与 https://books.google.com 相比,我得到的结果非常不相关。例如,这是我通过单词sher搜索得到的名单(主要是期待类似福尔摩斯)。
`她说是的;哦她发光食谱;她能知道什么?;她 - 狼;谋杀她写了;我的母亲她杀了我,我的父亲他吃了我;妇女必须知道的22件事情,如果她爱上一个男人与阿斯伯格综合征;她在哪里舞;以色列 - 巴勒斯坦和谈谈判,1999 - 2001年
如你所见,那里甚至没有最相关的标题。如果你在谷歌图书网站上输入Sher,你会得到绝对正确的相关建议。我对Google API有正确的理解吗?我的代码有什么问题?
var request ='https://www.googleapis.com/books/v1/volumes ;
var outputbookslistshow = 0; ('keyup',function(){
if(outputbookslistshow == 0){
outputbookslistshow = 1;
$('#b $ b $('#myTextArea' outputgbooksrec')。show(300); //它是一个用于输出标题的div
$('#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
以下是 工作小提琴 使用Google的 https://suggestqueries.google.com/complete/search
参数:
输出/客户端#toolbar=> xml,firefox=> json,chrome=> jsonp
ds#要搜索的网站(bo为书籍,yt为youtube ...)
q#搜索词:sher
查询: $ b
首先要认识到的是,当Google提出建议时,它们不是它会显示给您的结果。
搜索结果是相关的,如果相关条款包含在您的查询中。 > 建议假设您的查询不完整,因此请将您的查询与其他查询进行比较,以猜测您的查询的完成版本可能是什么。
当我在 http://books.google.com 上搜索sher时,我看到的结果是:
- 以色列 - 巴勒斯坦和谈谈判,1999 - 2001年
- 超越中立:完美主义和政治
- 沙漠
- 拒绝选择!:使用您的所有兴趣,激情,...
原因是作者:在前三个George Sher的情况下,以及在f第四芭芭拉谢尔。这是所希望的行为,因为当我搜索sher时,我不希望Sherlock的结果掩盖George Sher。 $ b H1> 2。解决方案
Google对于其建议也有一种API。有关它的一些信息可在此处找到。更重要的是,使用开发者工具,你可以准确地看到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
:
客户=书籍
ds = bo
q = sher
callback = _callbacks _._ 1id33zyi5
- 客户端决定了结果的类型(XML [工具],JSON [firefox],JSONP [chrome])
- ds 限制搜索到特定网站(books [bo], youtube [yt] etc。)。
- q 当然是查询文本
- callback 是一个用于JSONP的参数(它有一些与JSON的重要区别)。不要太担心,因为jQuery可以为你处理这个问题。
CORS:由于您正在从不是google.com的域发出请求,因此您将收到 Access-Control-Allow-Origin
错误。这是一项旨在防止 XSS 的安全措施。为了解决这个问题,你需要使用JSONP。
使用jQuery,我们不必担心回调,因此我们将客户端参数更改为 chrome
并使用这个最终查询:
https://suggestqueries.google.com/complete/search?client=chrome&ds=bo&q=sher
以下工作示例:在本例中,您可能需要注意
google:suggestrelevance
键,这是使用JSONP的额外好处(Google只会以JSONP数据的形式返回这些信息)。
var requestUrl =https://suggestqueries.google.com/complete/search?client=chrome&ds=bo&q=\";var xhr; $(docum ();}(input,#query,function(){typewatch(function(){//这里是关于var queryTerm = $(#query)。 $( #指标)显示()。 if(xhr!= null)xhr.abort(); xhr = $ .ajax({url:requestUrl + queryTerm,dataType:jsonp,success:function(response){$(#indicator)。hide(); $(#response)。html(syntaxHighlight response));}}); },500);}); / * * ---------你只需要这行上面的内容--------- * / $(document).ready(function(){ $(#indicator)。hide();}); //只是为了好玩,一些语法突出显示... // Credit:http://stackoverflow.com/a/7220510/123415function syntaxHighlight(json){if (typeof json!='string'){json = JSON.stringify(json,undefined,2); }替换(/< / g,'& lt;')。替换(/> / g,'& gt; ); return json.replace(/((\\u [a-zA-Z0-9] {4} | \\ [^ u] | [^ \\])*(\ ?S * :) | \b(真|假| 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>';});} //自动搜索(停止输入时)/ /函数:http://stackoverflow.com/a/2219966/123415var typewatch =(函数(){var定时器= 0;返回函数(回调,毫秒){清除超时(定时器);计时器= setTimeout(回调,毫秒); };})();
/ * *安全忽略:*这只是为了让东西看起来隐约得体* / body {padding:10px;} div * {vertical-align:top;}#indicator {display:inline -块;背景:无重复中心/ 100%网址('http://galafrica.actstudio.ro/img/busy_indicator.gif');宽度:17px; height:17px; margin:3px;} / * * * CREDIT:* http://stackoverflow.com/a/7220510/123415 * / 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 /库/ jquery的/ 2.1.1 / jquery.min.js>< /脚本>< DIV> < input type = text id =queryplaceholder =Start typing .../>< span id =indicator>< / span>< / div>< pre id =response >< / pre>
I am trying to build book title recommendation system using Google Books API. Unfortunately results I get are extremely irrelevant comparing to https://books.google.com . For example that's a list I get from search by word "sher"(looking forward to something like Sherlock Holmes primarily).
`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`
As you see, there is no even most relevant title. If you type "Sher" at google books website you'll get absolutely correct relevant recommendations. Have I understood Google API right? What is wrong in my code?
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
Here's a working fiddle using Google's https://suggestqueries.google.com/complete/search
Parameters:
output/client # "toolbar" => xml, "firefox" => json, "chrome" => jsonp
ds # which site to search in ("bo" for books, "yt" for youtube...)
q # search term: "sher"
Query:
https://suggestqueries.google.com/complete/search?output=firefox&ds=bo&q=sher
Results:
["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. Suggestions vs Search Results
The first thing to realise is that when Google makes suggestions, they are not the results it would show you if you were to hit enter.
Search Results are relevant if relevant terms are included in your query.
Suggestions assume that your query is incomplete and therefore compare your query to other queries to guess what the completed version of your query might be.
When I search "sher" on http://books.google.com the results I see are:
- The Israeli-Palestinian Peace Negotiations, 1999-2001
- Beyond Neutrality: Perfectionism and Politics
- Desert
- Refuse to Choose!: Use All of Your Interests, Passions, ...
The reason for this is the author: In the case of the first three, "George Sher" and in the case of the fourth "Barbara Sher". This is desired behaviour because when I search "sher" I don't want "Sherlock" results burying "George Sher".
2. The Solution
Google has a kind of API for its suggestions as well. Some information about it can be found here. More significantly, using the developer tools however, you can see precisely what Google is doing.
Using Developer Tools: Inspect the https://books.google.com page (CTRL+SHIFT+i in Chrome). Go to the network tab and wait until everything is loaded.
When you begin typing, Google fires requests to the server which you will see populate in the list. When I typed "sher", Google sent this request:
https://suggestqueries.google.com/complete/search?client=books&ds=bo&q=sher&callback=_callbacks_._1id33zyi5
Look at the variables:
client = books
ds = bo
q = sher
callback = _callbacks_._1id33zyi5
- client determines the type of result that you receive (XML [toolbar], JSON [firefox], JSONP [chrome])
- ds limits the search to a specific site (books [bo], youtube [yt] etc.).
- q is, of course, the query text
- callback is a paramater used for JSONP (which has some important differences to JSON). Don't worry too much about it because jQuery can handle this for you.
I pieced together bits of information on these parameters by looking at this request and by reading this and this.
CORS: Because you are making a request from a domain that's not google.com, you are going to get an Access-Control-Allow-Origin
error. This is a security measure trying to prevent XSS. To get around this problem, you will need to use JSONP.
Using jQuery, we needn't worry about the callback so let's change the client parameter to chrome
and use this final query:
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: http://stackoverflow.com/a/7220510/123415
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
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: http://stackoverflow.com/a/2219966/123415
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:
* http://stackoverflow.com/a/7220510/123415
*/
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>
这篇关于使用Google Books API的建议结果无关紧要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!