# Data structure that allow efficient tag based lookups

I am looking for a highly efficient data structure for storage of data similar to the following.

Id    Tags   Order1 Order2
--------------------------
1     1,2     1      1
2     2,5     2      3
3     1,7     4      7
4     6       3      0


I need to be able to query this structure in such a way that it would give me a list of all ids containing an expression of tags - supporting AND and OR and NOT operations. Eg. ((1 or 2) and not 7)

I also need to be able to specify the ordering of the results (Order1 or Order2) and be able to specify maximum rows returned with an optional offset. Performance for the fetch of the first 30-100 results is key.

Finally, I need a cheap way to lookup "tag relations" for example I want to know which tags "relate" to tags (1 OR 2) and in what frequency. Meaning which tags appear in the same set as 1 OR 2 ... ordered by frequency.

Any idea of what data structure (or set of structures) would be highly efficient for this kind of work?

(I would like to use this as a proof of concept for redesigning the tagged pages of the SE family of sites)

-
Just a comment (perhaps trivial). Why don't you rely on a relational database management system? You can define a table with the <id,tag> pairs and add an index on the tag column. Then you can use standard SQL queries for extracting data. The RDBMS will efficiently do the "dirty" work of query optimization and output sorting. –  Marzio De Biasi May 5 '11 at 10:29
@Vor, the expressions are incredibly inefficient at high scale, the self joins become nightmarish queries. –  Sam Saffron May 5 '11 at 12:33
@Sam: ok. Your task is quite common so I thought that a good RDBMS (with a data mining tool) could do the job. I leave the floor to a data structure expert. :-) –  Marzio De Biasi May 5 '11 at 13:39
I believe allowing all combinations of AND, OR, NOT is going to make it difficult to create a data structure that doesn't list through all the items (perhaps it could be limited to 3-CNF?). If no such limitation exists, then perhaps just run through the records (in the specified order) until you find 30-100 that pass your tag requirements. Although, in general, I agree with Vor's suggestion of using a database to do the heavy lifting for you. –  bbejot May 5 '11 at 15:04
Not an expert, but I think if you don't put some restrictions on the way you can ask about tags then it is going to be difficult. Limiting them to CNFs (as bbejot suggested) is one way, another is restricting the number of different tags that query can ask about by a small number (say 6). –  Kaveh May 5 '11 at 23:19

This is not exactly an answer of an efficient data structure, but rather an elaboration on the comments of @bbejot and @Kaveh giving a hand-waving argument for why given the current question we should not expect something that does a lot better than searching the whole database. The argument is based on a reduction from SAT, the exponential time hypothesis, and a lot of hand-waving.

Assume we have upto $n$ different tags, then we can think of each id as being associated with a bitvector $x$ of length $|x| = n$ where $x_j = 1$ if we have the $j$-th tag, and $x_j = 0$ otherwise. Since there is no real restrictions on what the database looks like, I can assume it has ids $1$ through $2^n$ with the $k$-th id having an associated tag vector of $k$ written in binary. The order fields can be arbitrary, since they only make the problem harder. Now, if we are given an arbitrary query of $AND$, $OR$, and $NOT$s then this is just asking a SAT question on $n$ variables. By the exponential time hypothesis, we can't expect this to be much faster than $2^n$... or in other words, we can't expect this to be much faster than searching the whole database.

We shouldn't expect efficient search in the length of the query (by reduction to SAT). We also shouldn't expect much better than looking at all the items in the database by the exponential time hypothesis.

To hope for an efficient data-structure for this question, we will have to make some serious assumptions on the structure of the database that are not made in this question. For instance, if we assume a special structure on the queries (such as CNF) then we can hope for something more efficient. An alternative assumption is on the structure of the database. We could probably assume that given $n$ tags, only a small fraction of the tags will be present on any given id (say a logarithmicly few $1$s). This is not an unreasonable assumption given the application of tagged questions (what use are tags if almost every single tag is used for a question).

-
Good observation. Each question has at most 5 tags, so a query about tags is equivalent to a 5-CNF. –  Kaveh May 7 '11 at 4:39
thank you! yes we can assume 5-CNF here further more, tagging behavior is not random. In general people will tag stuff with the most common tags, so that will allow for a few other shortcuts. –  Sam Saffron May 7 '11 at 11:22
@Kaveh, we ended up rolling an in memory structure. There are a few non-trivial shortcuts, sort is a bottleneck, using heap sort or a modified quick sort allows you to efficiently select top N without needing to perform a full sort. pre-calculating sorts allows you to pick pivots more efficiently and avoid sorts when a full scan is needed. multithreading speeds up selections. a lot of work can be deferred to the background before users interact with the structures. amazingly our in-memory structures are averaging 0ms for a search on the stack overflow data set. –  Sam Saffron May 28 '11 at 12:15
@SamSaffron - Where's the MSO post detailing this feature? We've got a bug report here. –  Kevin Vermeer Oct 20 '11 at 15:41

This is a pretty straightforward answer, but I think effective:

A suggestive type for your datastructure: Map Tag ([Id],[Id]) where the two lists of Ids are ordered by order1 and order2 respectively. Maintaining and generating this structure has a cost, but queries on a single tag should be $O(log (n))$ in the number of tags. Storing the length of the lists with the lists would help with query optimization, and much better than an actual list would be a lazy bitvector which would make negation extremely cheap as well.

If you thrown in another map of type Map Id (Set Tag) then generating the related frequencies given a list of Ids should be $O(n * log (m))$ in the size of the list and the size of the sets of tags.

-
I am tending to agree that some very simple structures like a map spooled multiple times may be the best way to go here. memory is cheap and maintaining multiple caches is not too hard –  Sam Saffron May 7 '11 at 10:51