forked from sunspot/sunspot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
id_sharding_session_proxy.rb
70 lines (64 loc) · 2.18 KB
/
id_sharding_session_proxy.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
module Sunspot
module SessionProxy
#
# A concrete implementation of ShardingSessionProxy that determines the
# shard for a given object based on the hash of its class and ID.
#
# <strong>If you change the number of shard sessions that this proxy
# encapsulates, all objects will point to a different shard.</strong> If you
# plan on adding more shards over time, consider your own
# ShardingSessionProxy implementation that does not determine the session
# using modular arithmetic (e.g., IDs 1-10000 go to shard 1, 10001-20000 go
# to shard 2, etc.)
#
# This implementation will, on average, yield an even distribution of
# objects across shards.
#
# Unlike the abstract ShardingSessionProxy, this proxy supports the
# #remove_by_id method.
#
class IdShardingSessionProxy < ShardingSessionProxy
#
# The shard sessions encapsulated by this class.
#
attr_reader :sessions
alias_method :all_sessions, :sessions #:nodoc:
#
# Initialize with a search session (see ShardingSessionProxy.new) and a
# collection of one or more shard sessions. See note about changing the
# number of shard sessions in the documentation for this class.
#
def initialize(search_session, shard_sessions)
super(search_session)
@sessions = shard_sessions
end
#
# Return a session based on the hash of the class and ID, modulo the
# number of shard sessions.
#
def session_for(object) #:nodoc:
session_for_index_id(Adapters::InstanceAdapter.adapt(object).index_id)
end
#
# See Sunspot.remove_by_id
#
def remove_by_id(clazz, id)
session_for_index_id(
Adapters::InstanceAdapter.index_id_for(clazz, id)
).remove_by_id(clazz, id)
end
#
# See Sunspot.remove_by_id!
#
def remove_by_id!(clazz, id)
session_for_index_id(
Adapters::InstanceAdapter.index_id_for(clazz, id)
).remove_by_id!(clazz, id)
end
private
def session_for_index_id(index_id)
@sessions[index_id.hash % @sessions.length]
end
end
end
end