2010-10-10 41 views
0

LinkedIn提供了一種機制來說明用戶在最近的「x」天內是「n」次搜索條件的一部分。你如何去捕獲和存儲信息。您是否應該迭代搜索結果,並在搜索結果中添加適當的計數器,或者是否存在可以在較低級別(比應用層)更低級別捕獲的非侵入式機制如何查找並存儲用戶參與搜索條件的次數

回答

1

你可以做這樣的事情(http://pastie.org/1211302):

drop table if exists users; 
create table users 
(
user_id int unsigned not null auto_increment primary key, 
username varbinary(32) unique not null 
) 
engine=innodb; 

insert into users (username) values ('f00'),('bar'),('foobar'),('alpha'),('felix'); 

drop table if exists user_hits; 
create table user_hits 
(
hit_id int unsigned not null auto_increment primary key, 
hit_date datetime not null, 
user_id int unsigned not null, 
key hit_date_user_idx(hit_date, user_id) 
) 
engine=innodb; 

drop procedure if exists user_search; 

delimiter # 

create procedure user_search 
(
in p_username varbinary(32) 
) 
begin 

    set p_username = trim(replace(p_username, '%','')); 

    create temporary table matches engine=memory 
    select * from users where username like concat(p_username,'%'); 

    insert into user_hits (hit_date, user_id) select now(), user_id from matches; 

    select * from matches order by username; 

    drop temporary table if exists matches; 

end # 

delimiter ; 

drop procedure if exists user_hits; 

delimiter # 

create procedure user_hits 
(
in p_user_id int unsigned, 
in p_day_interval smallint unsigned 
) 
begin 

select 
    user_id, 
    hit_date, 
    count(*) as hits 
from 
    user_hits 
where 
    hit_date between now() - interval p_day_interval day and now() and 
    user_id = p_user_id 
group by 
    hit_date, user_id; 

end # 

delimiter ; 

-- testing 

select * from users; 
select * from user_hits; 

call user_search('f00'); 

select * from user_hits; 

call user_search('f'); 

select * from user_hits; 

call user_hits(1,7); 
1

最簡單的方法是記錄所有搜索,然後統計(使用SQL)特定用戶出現的次數。東西的效果:SELECT COUNT(1) FROM search_log WHERE search_string = 'this-user-name'

這可能是數據然而實時查詢,一個不切實際的量,特別是如果你要計算的搜索,僅僅包括的用戶名(例如,「小狗,小貓,和此用戶名「)。在這種情況下,最直接的方法是在您的user表中簡單包含一個用於統計搜索的字段。然後,在處理每個搜索時,您可以查找其中的任何用戶名並遞增相應的計數器。

+0

不,我不知道發生搜索與用戶標識符(他們可能會像搜索,搜索我的一切某個公司或某個地點的人員,或公司中的某個指定人員)。因此,在這些情況下,雖然 – Sam 2010-10-10 15:03:19

+0

不知道用戶標識符,但您在運行搜索時必須知道哪些用戶符合搜索**(否則您無法顯示它們)。利用這個機會來增加你的'number_of_times_appeared_in_a_search'字段。 – VoteyDisciple 2010-10-10 15:04:38

+0

因此,解決方案將遍歷所有符合特定搜索條件的用戶並更新每個用戶計數器。有沒有辦法在數據庫級本身處理這個問題,而不是在應用程序層,我寧願避免邏輯迭代並更新每個用戶計數器,以滿足搜索條件中的所有用戶。這可能會減慢返回搜索結果所花費的時間。 – Sam 2010-10-10 15:17:24