Indexes: Indexing Compare Exchange Values


  • Compare exchange values can be loaded within an index using the value's key.

  • The index will update when the compare exchange value is updated, as well as when documents are modified in the indexed collection(s).

  • In this page:


Syntax

When creating an index using AbstractIndexCreationTask, use the method LoadCompareExchangeValue() to load a compare exchange value by its key.

//Load one compare exchange value
T LoadCompareExchangeValue<T>(string key);

//Load multiple compare exchange values
T[] LoadCompareExchangeValue<T>(IEnumerable<string> keys);

For javascript indexes, use the method cmpxchg(<key>).

Parameter Type Description
key string The key of a particular compare exchange value.
keys IEnumerable<string> The keys of multiple compare exchange values.


Examples

These indexes map the rooms in a hotel, as well as compare exchange values representing the guests in those rooms.

private class Compare_Exchange_Index : AbstractIndexCreationTask<HotelRoom>
{
    public class Result
    {
        public string Room;
        public string Guests;
    }

    public Compare_Exchange_Index()
    {
        Map = HotelRooms => from room in HotelRooms
                            let guests = LoadCompareExchangeValue<string>(room.RoomID)
                            select new Result
                            {
                                Room = room.RoomID,
                                Guests = guests
                            };
    }
}
private class Compare_Exchange_JS_Index : AbstractJavaScriptIndexCreationTask
{
    public Compare_Exchange_JS_Index()
    {
        Maps = new HashSet<string>
        {
            @"map('HotelRooms', function (room) { 
                var guests = cmpxchg(room.RoomID); 
                return { 
                    RoomID: room.RoomID, 
                    Guests: guests 
                };
            })",
        };
    }
}

Querying the Index

// Return all vacant hotel rooms
List<HotelRoom> vacantRooms = session
    .Query<HotelRoom, Compare_Exchange_Index>()
    .Where(x => RavenQuery.CmpXchg<string>(x.RoomID) == null)
    .OfType<HotelRoom>()
    .ToList();
// Return all vacant hotel rooms
List<HotelRoom> vacantRooms = await asyncSession
    .Query<HotelRoom, Compare_Exchange_Index>()
    .Where(x => RavenQuery.CmpXchg<string>(x.RoomID) == null)
    .OfType<HotelRoom>()
    .ToListAsync();
// Return the room occupied by VIP guests
List<HotelRoom> VIPRooms = session
    .Advanced.RawQuery<HotelRoom>(
        @"from Hotelrooms as room
        where room.Guests == cmpxchg('VIP')"
    )
    .ToList();