Skip to content

Commit e981599

Browse files
YuCai18caiyu
andauthored
Modify the ZAdd function in redis_zsets to read the array from back to front (#3108)
Co-authored-by: caiyu <[email protected]>
1 parent 1db2fbd commit e981599

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

src/storage/src/redis_zsets.cc

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -307,13 +307,17 @@ Status RedisZSets::ZAdd(const Slice& key, const std::vector<ScoreMember>& score_
307307
*ret = 0;
308308
uint32_t statistic = 0;
309309
std::unordered_set<std::string> unique;
310-
std::vector<ScoreMember> filtered_score_members;
311-
for (const auto& sm : score_members) {
312-
if (unique.find(sm.member) == unique.end()) {
313-
unique.insert(sm.member);
314-
filtered_score_members.push_back(sm);
310+
std::list<storage::ScoreMember> mid_score_members;
311+
for (auto it = score_members.rbegin(); it != score_members.rend(); ++it) {
312+
if (unique.find(it->member) == unique.end()) {
313+
unique.insert(it->member);
314+
mid_score_members.push_front(*it);
315315
}
316316
}
317+
std::vector<ScoreMember> filtered_score_members;
318+
for (auto &item : mid_score_members) {
319+
filtered_score_members.push_back(std::move(item));
320+
}
317321

318322
char score_buf[8];
319323
int32_t version = 0;

tests/integration/zset_test.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,26 @@ var _ = Describe("Zset Commands", func() {
233233
Member: "two",
234234
}}))
235235
})
236-
236+
// Caiyu's test: verify that zadd with multiple scores for the same member in
237+
//a single command only keeps the last score, consistent with Redis behavior
238+
It("should ZAdd with duplicate member in one command", func() {
239+
added, err := client.ZAdd(ctx, "myzset", redis.Z{
240+
Score: 100,
241+
Member: "one",
242+
}, redis.Z{
243+
Score: 98,
244+
Member: "one",
245+
}).Result()
246+
Expect(err).NotTo(HaveOccurred())
247+
Expect(added).To(Equal(int64(1)))
248+
249+
vals, err := client.ZRangeWithScores(ctx, "myzset", 0, -1).Result()
250+
Expect(err).NotTo(HaveOccurred())
251+
Expect(vals).To(Equal([]redis.Z{{
252+
Score: 98,
253+
Member: "one",
254+
}}))
255+
})
237256
It("should ZAdd bytes", func() {
238257
added, err := client.ZAdd(ctx, "zset", redis.Z{
239258
Score: 1,

0 commit comments

Comments
 (0)