ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Cassandra CQL: Find First Occurrence of Element in Sorted List

Cassandra CQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE TABLE user_activity (
2user_id uuid,
3activity_timestamp timestamp,
4activity_type text,
5details text,
6PRIMARY KEY (user_id, activity_timestamp)
7);
8
9-- Create a secondary index on activity_type to allow searching for specific activities.
10-- Note: Secondary indexes can have performance implications for high-cardinality columns.
11CREATE INDEX IF NOT EXISTS ON user_activity (activity_type);
12
13-- Function to find the timestamp of the first occurrence of a specific activity type for a user.
14-- This function assumes activity_timestamp is ordered chronologically.
15-- It searches for the earliest entry matching the activity_type.
16CREATE OR REPLACE FUNCTION find_first_activity_timestamp(
17target_user_id uuid,
18target_activity_type text
19)
20RETURNS timestamp
21LANGUAGE java
22AS $$
23// In a real Cassandra UDF, direct querying is not typical for performance reasons.
24// This is a conceptual representation of the logic.
25// A more idiomatic CQL approach would be a SELECT statement with LIMIT 1.
26
27// For demonstration, we'll simulate the search logic.
28// We'd ideally query for rows matching user_id and activity_type, ordered by timestamp.
29// The first row returned would contain the desired timestamp.
30
31// Example of a direct CQL query (preferred):
32// SELECT activity_timestamp FROM user_activity
33// WHERE user_id = ? AND activity_type = ?
34// ORDER BY activity_timestamp ASC
35// LIMIT 1;
36
37// If the query returns no rows, the element is not found or the user has no activities.
38// The function should return null in such cases.
39
40// Placeholder for conceptual logic:
41timestamp first_ts = null;
42// Assume we have a way to fetch rows matching the criteria.
43// If rows are fetched and ordered by timestamp, take the first one.
44// If no rows are fetched, first_ts remains null.
45
46return first_ts;
47$$
48;
49
50-- Example of how to use the function (conceptually):
51-- SELECT find_first_activity_timestamp(uuid('a1b2c3d4-e5f6-7890-1234-567890abcdef'), 'login');
52
53-- The direct and recommended CQL query:
54-- SELECT activity_timestamp FROM user_activity
55-- WHERE user_id = uuid('a1b2c3d4-e5f6-7890-1234-567890abcdef')
56-- AND activity_type = 'login'
57-- ORDER BY activity_timestamp ASC
58-- LIMIT 1;
59
60-- Edge case: User has no activities at all.
61-- SELECT activity_timestamp FROM user_activity
62-- WHERE user_id = uuid('00000000-0000-0000-0000-000000000000')
63-- AND activity_type = 'login'
64-- ORDER BY activity_timestamp ASC
65-- LIMIT 1;
66-- This will return an empty result set (null timestamp).
67
68-- Edge case: User has activities, but not of the target type.
69-- INSERT INTO user_activity (user_id, activity_timestamp, activity_type, details) VALUES (uuid('aabbccdd-eeff-0011-2233-445566778899'), toTimestamp(now()), 'logout', 'User logged out.');
70-- SELECT activity_timestamp FROM user_activity
71-- WHERE user_id = uuid('aabbccdd-eeff-0011-2233-445566778899')
72-- AND activity_type = 'login'
73-- ORDER BY activity_timestamp ASC
74-- LIMIT 1;
75-- This will also return an empty result set (null timestamp).
76
77-- Edge case: User has multiple activities of the target type.
78-- INSERT INTO user_activity (user_id, activity_timestamp, activity_type, details) VALUES (uuid('aabbccdd-eeff-0011-2233-445566778899'), toTimestamp(now()) - 10000000, 'login', 'First login.');
79-- INSERT INTO user_activity (user_id, activity_timestamp, activity_type, details) VALUES (uuid('aabbccdd-eeff-0011-2233-445566778899'), toTimestamp(now()), 'login', 'Second login.');
80-- SELECT activity_timestamp FROM user_activity
81-- WHERE user_id = uuid('aabbccdd-eeff-0011-2233-445566778899')
82-- AND activity_type = 'login'
83-- ORDER BY activity_timestamp ASC
84-- LIMIT 1;
85-- This will return the timestamp of the 'First login.' entry.
Algorithm description viewbox

Cassandra CQL: Find First Occurrence of Element in Sorted List

Algorithm description:

This scenario involves writing a Cassandra CQL query to find the timestamp of the earliest occurrence of a specific user activity. The data is structured such that user activities are ordered by timestamp within a user's partition. The challenge lies in efficiently searching for a particular activity type and retrieving only the first instance, especially when dealing with potentially large datasets and the use of secondary indexes. This is relevant for analyzing user behavior patterns and auditing.

Algorithm explanation:

The most efficient approach in Cassandra for this problem is to use a `SELECT` query with a `WHERE` clause filtering by `user_id` and `activity_type`, followed by an `ORDER BY activity_timestamp ASC` and `LIMIT 1`. The `WHERE` clause targets the relevant partition and the indexed column. `ORDER BY` ensures chronological sorting, and `LIMIT 1` stops the scan as soon as the first matching record is found. The time complexity depends on the effectiveness of the secondary index and the number of rows scanned before finding the first match. In the best case (if the index is highly selective and the element is found early), it can be close to O(log N) or O(1) for the index lookup plus O(1) for the first row fetch. In the worst case, if many rows match `activity_type` but are not the `user_id` partition, it could approach O(N) for the scan within the partition. Space complexity is O(1) as only the result is returned. Edge cases like an empty partition or no matching activity type are handled by returning an empty result set, which translates to a `null` timestamp.

Pseudocode:

Define a table 'user_activity' with 'user_id' as partition key and 'activity_timestamp' as clustering key.
Create a secondary index on 'activity_type'.
To find the first occurrence of 'target_activity_type' for 'target_user_id':
  Construct a CQL query:
    SELECT activity_timestamp
    FROM user_activity
    WHERE user_id = target_user_id
    AND activity_type = target_activity_type
    ORDER BY activity_timestamp ASC
    LIMIT 1;
  Execute the query.
  If the query returns a row, return the 'activity_timestamp' from that row.
  If the query returns no rows, return null.