Returning Specific Fields

Returning Specific Fields (Narrow Your Search)

Redis can have a large number of elements in a RediSearch document.  You can limit your search queries to return only specific elements.  (This is similar to the SQL Select col1, col2, col3 ... from..     statement).  

In this example, we modify the code to return only the following fields:

  customerID, customerName,  address,  orderID,  productName

In this code fragment, we have hard-coded items that you will normally pass in as parameters.

 public class DynamicDoc
{
    public string id { get; set; }
    public double score { get; set; }
    public Dictionary<string, object> payload{ get; set; }
}
 //**************************************************************      
        [HttpGet]
        [Route("api/search/orders/restrictfields")]
            public async Task<List<DynamicDoc>> SearchOrdersRestrictFields()
        {
            string searchString = "Queso";
            IDatabase db = _connectionMultiplexer.GetDatabase();

            NRediSearch.Query query = new NRediSearch.Query(searchString);

            string[] returnFields = { "customerID", "customerName","address", "orderID", "productName" };
           
            query.ReturnFields(returnFields);

            query.WithPayloads = true;

            SearchResult res = await _rediSearchClient.SearchAsync(query);

            List<DynamicDoc> dynamicDocs = new List<DynamicDoc>();

            foreach (Document doc in res.Documents)
            {
                IEnumerable<KeyValuePair<string, RedisValue>> record = doc.GetProperties();
                string jsonRecord = JsonConvert.SerializeObject(record);
                Dictionary<string, object> _record = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonRecord);
 
                DynamicDoc dynamicDoc = new DynamicDoc()
                {
                     id = doc.Id,
                     score = doc.Score,
                     payload = _record
                };
                dynamicDocs.Add(dynamicDoc);
            }
            return dynamicDocs;
        }
Returning Specific Fields

         

Notes on the above code

  1. We create a class DynamicDoc to hold the returned record(s)
  2. Lines 17-19 specify the fields to return and add it to the query.
  3. The SearchResults are NOT cast to the CustomerOrders class used in the previous examples. Doing this could result in a significantly large number of unrequested null properties being returned to the caller. Instead, we cast the document record (Payload) to a Dictionary<string,object>

The returned records show only the requested fields in the payload; it looks like this;

[
    {
        "id": "northwind:orders_temp2147",
        "score": 1,
        "payload": {
            "customerID": "RATTC",
            "customerName": "Rattlesnake Canyon Grocery",
            "address": "2817 Milton Dr.",
            "orderID": "11077",
            "productName": "Queso Manchego La Pastora"
        }
    },
    {
        "id": "northwind:orders_temp2131",
        "score": 1,
        "payload": {
            "customerID": "PERIC",
            "customerName": "Pericles Comidas clásicas",
            "address": "Calle Dr. Jorge Cash 321",
            "orderID": "11073",
            "productName": "Queso Cabrales"
        }
    }
]
    
Sample Restricted Results (showing 2 records)

The above query will return results for all the documents that match the the query.  To restrict the query to specific documents keys we then make the following sample modifications to the code:

	string[] returnFields = { "customerID", "customerName","address", "orderID", "productName" };
	string[] limitKeys = { "northwind:orders_temp2063", "northwind:orders_temp2147" };
           
	query.LimitKeys(limitKeys);
	query.ReturnFields(returnFields);

	query.WithPayloads = true;

Notes on above

  1. lines 2-4 are added to specify the document keys (ids)
  2. This query is then the equivalent of the SQL:

SELECT customerID, customerName, address, orderID, productName from tablename
where documentKey IN ('northwind:orders_temp2063', 'northwind:orders_temp2147')