3
votes

I'm storing documents of several different types (entity types?) in a single collection. What would be the best way get all documents of a certain type (like you would do with select * from a table).

Options I see so far:

  1. Include the type as a property. But that would mean a looking into every document when getting the documents, right?
  2. Prepend the type name to the document id and try searching by id with typename*.

Is there a better way to do this?

3

3 Answers

5
votes

There's no built-in entity-type property, but you can certainly create your own, and ensure that it's indexed. At this point, it's as straightforward as adding a WHERE clause:

WHERE docs.docType = "SomeType"

Assuming it's a hash-based index, this should provide efficient lookups and filter out unwanted document types.

While you can embed the type into a property (such as document id), you'd then have to do partial string matches, which won't be as efficient as an indexed-property comparison.

If you're curious to know what this query is costing you, the RU value is displayed both in the portal and via x-ms-request-charge return header.

2
votes

I agree with David's answer and using a single docType field is what I did when I first started using DocumentDB. However, there is another option that I started using after doing some experiments. That is to create an is<Type> field and setting its value to true. This is slightly more efficient for queries than using a single string field, because the indexes themselves are smaller partial indexes, but could potentially take up slightly more storage space.

The other advantage to this approach is that it provides advantages for inheritance and mixins. For example, I have both isLookup=true and isState=true on certain entities. I also have other lookup types. Then in my application code, some behaviors are common for all lookup fields and other behaviors are only applicable to the State type.

1
votes

If you index the type property on the collection, it will not be a complete scan.