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)

  • 1
    $\begingroup$ 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. $\endgroup$ May 5, 2011 at 10:29
  • 1
    $\begingroup$ @Vor, the expressions are incredibly inefficient at high scale, the self joins become nightmarish queries. $\endgroup$ May 5, 2011 at 12:33
  • $\begingroup$ @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. :-) $\endgroup$ May 5, 2011 at 13:39
  • 1
    $\begingroup$ FYI, this is the standard issue RDBMS have i.imgur.com/hym3p.png ... to figure out tag relations the algorithm is a very naive, scan + hash lookup. Which it horribly expensive. Similar issues exist around the expressions $\endgroup$ May 5, 2011 at 23:46
  • 1
    $\begingroup$ @Vor that is possible, been thinking of ways to optimise this for common cases, one other idea I had was storing a bitmap of the most common N tags, that way I could pull any combination for the common tags in a single sweep. $\endgroup$ May 6, 2011 at 8:59

2 Answers 2


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).

  • $\begingroup$ Good observation. Each question has at most 5 tags, so a query about tags is equivalent to a 5-CNF. $\endgroup$
    – Kaveh
    May 7, 2011 at 4:39
  • $\begingroup$ 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. $\endgroup$ May 7, 2011 at 11:22
  • 1
    $\begingroup$ @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. $\endgroup$ May 28, 2011 at 12:15
  • $\begingroup$ @SamSaffron - Where's the MSO post detailing this feature? We've got a bug report here. $\endgroup$ Oct 20, 2011 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.

  • $\begingroup$ 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 $\endgroup$ May 7, 2011 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.