【问题标题】:Results of recommendations using Google Books API are irrelevant使用 Google Books API 的推荐结果无关紧要
【发布时间】:2015-10-28 20:00:23
【问题描述】:

我正在尝试使用 Google Books API 构建书名推荐系统。 不幸的是,与 https://books.google.com 相比,我得到的结果非常无关紧要。例如,这是我通过单词“sher”搜索得到的列表(主要期待像夏洛克福尔摩斯这样的东西)。

`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>";
        } 
        })
        }

    });

【问题讨论】:

标签: javascript jquery json google-api google-books


【解决方案1】:

0。 TLDR

这是一个 working fiddle 使用 Google 的 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 提出建议时,它们并不是您按 Enter 键时会显示的结果。

如果您的查询中包含相关字词,则

搜索结果是相关的。

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

当我在 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 页面(在 Chrome 中为 CTRL+SHIFT+i) .转到网络选项卡并等待所有内容加载完毕。

当您开始输入时,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
  • 客户端确定您收到的结果类型(XML [工具栏]、JSON [firefox]、JSONP [chrome])
  • ds 将搜索限制在特定网站(书籍 [bo]、youtube [yt] 等)。
  • q 当然是查询文本
  • callback 是用于 JSONP 的参数(其中有一些 important differences to JSON)。不用太担心,因为 jQuery 可以为您处理。

通过查看此请求并阅读thisthis,我将有关这些参数的信息拼凑在一起。

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;

$(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, '&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: 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>

【讨论】:

  • XMLHttpRequest 无法加载 suggestqueries.google.com/complete/…。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'localhost:8888' 因此不允许访问。
  • @Vinand 我添加了一个小提琴并更新了(使用 JSONP),如果您仍然遇到问题,请告诉我...
  • 效果很好,但是有什么方法可以获取每个标题的附加信息吗?就像如果我们使用通常的搜索我们可以得到 isbn、coverurl、author 和其他 volumeInfo?还是唯一的方法是搜索选择的建议?
  • @Vinand 听起来您现在正在询问界面,这远远超出了这个问题的范围。不过,您将需要提出其他请求(您甚至可以使用 google api 根据您从我的代码中获得的建议进行搜索)。你如何展示和呈现这是另一个问题。
  • @Vinand 我只能推测,但也许谷歌对帮助人们提供建议不感兴趣——如果你想使用谷歌搜索,请使用谷歌搜索。当您想到产品时,Google 会为实际数据提供一个 API。
猜你喜欢
  • 2017-09-07
  • 2012-07-07
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2013-01-12
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多