如何使用typeahead.js与大型数据库 [英] How to use typeahead.js with a large database

查看:108
本文介绍了如何使用typeahead.js与大型数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10000地址和5000人的大型数据库。

I have a large database of 10,000 addresses and 5,000 people.

我希望让用户在数据库中搜索任何地址或用户。我想使用Twitter的预输入建议的结果,因为他们输入文字。

I want to let users search the database for either an address or a user. I'd like to use Twitter's typeahead to suggest results as they enter text.

请参阅NBA的例子在这里:<一href="http://twitter.github.io/typeahead.js/examples">http://twitter.github.io/typeahead.js/examples.

See the NBA example here: http://twitter.github.io/typeahead.js/examples.

据我所知,prefetching 15,000种不会是从转速和负荷的角度来看最优的。什么将是一个更好的方式,试图实现这一目标?

I understand that prefetching 15,000 items would not be optimal from a speed and load standpoint. What would be a better way to try and achieve this?

推荐答案

既然没有人做任何回答,我将与我的建议,然后继续前进。

Since no one made any answer, I will go ahead with my suggestion then.

我觉得你的大数据库最适合使用远程 typeahead.js 。简单的例子:

I think the best fit for your big database is using remote with typeahead.js. Quick example:

$('#user-search').typeahead({
    name: 'user-search',
    remote: '/search.php?query=%QUERY' // you can change anything but %QUERY
});

当你键入输入#用户搜索它会发送Ajax请求的页面字符它所做的是的search.php 与查询作为输入的内容。

What it does is when you type characters in the input#user-search it will send AJAX request to the page search.php with query as the content of the input.

的search.php 您可以搭乘此查询,并期待它在你的数据库:

On search.php you can catch this query and look it up in your DB:

$query = $_GET['query'].'%'; // add % for LIKE query later

// do query
$stmt = $dbh->prepare('SELECT username FROM users WHERE username LIKE = :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();

// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
    $results[] = $row;
}

// and return to typeahead
return json_encode($results);

当然,由于你的数据库是相当大的,你应该优化您的SQL查询的查询速度更快,也许缓存的结果,等等。

Of course since your DB is quite big, you should optimize your SQL query to query faster, maybe cache the result, etc.

在预输入端,以减少负载来查询数据库,你可以指定的minLength 限制

On the typeahead side, to reduce load to query DB, you can specify minLength or limit:

$('#user-search').typeahead({
    name: 'user-search',
    remote: '/search.php?query=%QUERY',
    minLength: 3, // send AJAX request only after user type in at least 3 characters
    limit: 10 // limit to show only 10 results
});

因此​​,它并不真正的问题有多大你的数据库是,这种方法应该很好地工作。

So it doesn't really matter how big your DB is, this approach should work nicely.

这是PHP的一个例子,但它当然应该是相同的无论后台有。希望得到您的基本思路。

This is an example in PHP but of course it should be the same for whatever backend you have. Hope you get the basic idea.

这篇关于如何使用typeahead.js与大型数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆