-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcouchrest_api_example.rb
108 lines (96 loc) · 2.5 KB
/
couchrest_api_example.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
require 'rubygems'
require 'couchrest'
require 'couchrest_model'
require 'json'
server = CouchRest.new
class JobOpening < CouchRest::Model::Base
use_database "job_openings"
property :title
property :location
property :skills
design do
view :by_title
view :by_location,
:map =>
"function(doc) {
emit(doc.location, 1);
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
view :by_skill,
:map =>
"function(doc) {
doc.skills.forEach(function(skill) {
emit(skill, 1);
});
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
view :by_skill_and_location,
:map =>
"function(doc) {
doc.skills.forEach(function(skill) {
emit([skill, doc.location], 1);
});
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
end
end
def store(location, skills)
opening = JobOpening.new({
:title => "job opening",
:location => location,
:skills => skills
})
opening.save
end
store("Amsterdam", ["javascript", "nodejs", "grunt", "karma"]);
store("Amsterdam", ["javascript", "nodejs", "grunt"]);
store("Amsterdam", ["javascript", "nodejs"]);
store("Amsterdam", ["javascript"]);
store("Berlin", ["javascript", "nodejs", "grunt", "karma"]);
store("Berlin", ["javascript", "nodejs", "grunt"]);
store("Berlin", ["javascript", "nodejs"]);
store("Paris", ["javascript", "nodejs", "grunt", "karma"]);
store("Paris", ["javascript", "nodejs", "grunt"]);
store("London", ["javascript", "nodejs", "grunt", "karma"]);
def top_locations
JobOpening.by_location.reduce.group_level(1).rows.sort do |x, y|
y.value <=> x.value
end.map do |x|
[x["key"], x["value"]]
end
end
def top_skills
JobOpening.by_skill.reduce.group_level(1).rows.sort do |x, y|
y.value <=> x.value
end.map do |x|
[x["key"], x["value"]]
end
end
def top_locations_for_skill(skill)
skills_and_locations = JobOpening.by_skill_and_location.reduce.group_level(2)
locations_and_count = skills_and_locations.rows.select do |row|
row["key"][0] == skill
end.map do |s|
[s["key"][1], s["value"]]
end.sort do |x, y|
y[1] <=> x[1]
end
end
puts "Top locations:"
p top_locations.take(2)
puts "Top skills:"
skills = top_skills.take(2)
p skills
skills.each do |skill|
puts "Skill '#{skill[0]}'"
p top_locations_for_skill(skill[0])
end