Skip to content

Instantly share code, notes, and snippets.

@sourcec0de
Last active December 20, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sourcec0de/6065696 to your computer and use it in GitHub Desktop.
Save sourcec0de/6065696 to your computer and use it in GitHub Desktop.
NQL Advanced Searching and Querying

Nutritionix Querying Language (NXQL)

NXQL allows developers to write more advanced queries against our data pool. Examples of what you can do with an advanced query:

  • Filter items by their type (show ONLY USDA items or ONLY CPG items)
  • Filter nutrient ranges (>100 calories AND <500 calories)

All requests are POST and require a valid JSON object be sent to https://api.nutritionix.com/v1_1/search You can paste any of the below JSON examples into this curl request and they will retrieve results assuming you have added your appKey, and appId.

Request Requirements

  • Must provide valid appId and appKey
  • Must provide filters, queries, or query properties in your JSON object
  • Must set Content-Type to application/json
curl -XPOST https://api.nutritionix.com/v1_1/search -H 'Content-Type: application/json' -d'
{
 "appId":"YOUR_API_ID",
 "appKey":"YOUR_API_KEY",
 "query":"Cookies `n Cream"
}
'

Filtering Item Type and sorting by score

This example will yeild only CPG items Item Types(item_type)

  • 1 = Restaurant
  • 2 = CPG (packaged foods with barcodes)
  • 3 = USDA
/**
  *
  * Ensure you pass your API credentials
  * Select the fields you want to return
  * Set the sorting mechanism
  * Apply some filters to the data
  *
  **/
{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",  
  "fields":["item_name","brand_name","upc"],
  "sort":{
    "field":"_score",
    "order":"desc"
  },
  "filters":{
    "item_type":2
  }
}

or you want all the item_types except restaurant items

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "filters":{
    "not":{
     "item_type":2
    }
  }
}

Range Filters

You can filter numeric_fields using several operators

  • gt
  • gte
  • lt
  • lte

Or

  • from
  • to
{
 "appId":"YOUR_APP_ID",
 "appKey":"YOU_APP_KEY",
 "filters"{
  "nf_calories":{
   "from":100,
   "to":50
  },
  "nf_sodium":{
   "lte":200
  }
 }
}

Nutritionix Search

You can use the default search where we apply boosting, and multi search factors to yeild the most relavent results to your users.

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "query":"Starbucks Frapucino"
}

Wild Card Searches

This query will yeild starbucks frapucino results

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "query":"Star* Frap*"
}

Different Boolean Search Operators

This query will yeild results that have starbucks or frapucino Available Operators

  • OR
  • AND (Default)
{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "query":"Starbucks OR Frappuccino*"
}

Custom Multi Field Search

If you want to search specific words across multiple fields

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOU_APP_KEY",
  "queries":{
    "item_name":"Kids Fries",
    "brand_name":"McDonalds"
  }
}

Filter to a specific brand, and paginate the results

On the API /:version/search GET endpoint we have the results default sorting by _score. Document scores can very sometimes, so to keep your search results consistent you can sort on a field that dosn't change.

{
  "appId":"YOUR_APP_ID",
  "appKey":"YOUR_APP_KEY",
  "fields":["item_name","brand_name","nf_calories","nf_sodium","item_type"],
  "offset":250,
  "limit":50,
  "sort":{
    "field":"item_name.sortable_na",
    "order":"asc"
  },
  "filters":{
   "brand_id":"513fbc1283aa2dc80c00001a"
  }
}'

NOTE -- item_name.sortable_na This field is the items original name, untouched by our texted analyzers. It can also be accessed on brand_name as well. I.E (brand_name.sortable_na) This query will give you the same results every time since you are sorting on a static field.

Advanced Query Full Example

Lets get really fancy with it Here is the breakdown for this search

  • appId
  • appKey
  • fields (an array of item attributes you want to return)
  • offset (The starting point in the result set for paging)
  • limit (The max number of results to be returned in the page)
  • sort (the field who's numerical value you want to sort by in descending order)
  • min_score (the minimum score that you want any returned document to have)
  • query (A phrase with special operators OR ~ *)
  • filters.not.item_type:2 (ensuring that we don't pay any attention to CPG data)
  • filters.nf_calories (a range filter to and from a certain numerical range)
  • filters.nf_sodium (a boolean filter for less than)
{
  "appId": "YOUR_APP_ID",
  "appKey": "YOUR_APP_KEY",
  "fields": [
    "item_name",
    "brand_name",
    "nf_calories",
    "nf_sodium",
    "item_type"
  ],
  "offset": 0,
  "limit": 50,
  "sort": {
    "field": "nf_calories",
    "order": "desc"
  },
  "min_score": 0.5,
  "query": "starbucks AND frap*",
  "filters": {
    "not": {
      "item_type": 2
    },
    "nf_calories": {
      "from": 0,
      "to": 400
    }
  }
}

This search yeild these results.

{
    "total": 3,
    "max_score": null,
    "hits": [
        {
            "_index": "4qnk4vry5gujjxptu5rg",
            "_type": "item",
            "_id": "513fc9c6673c4fbc26001dca",
            "_score": null,
            "fields": {
                "nf_sodium": 100,
                "item_name": "Starbucks Coffee Frappuccino (Yield: 1 bottle)",
                "brand_name": "Gandolfo's New York Delicatessen",
                "nf_calories": 200,
                "item_type": 1
            },
            "sort": [
                200
            ]
        },
        {
            "_index": "4qnk4vry5gujjxptu5rg",
            "_type": "item",
            "_id": "513fc9c6673c4fbc26001dcd",
            "_score": null,
            "fields": {
                "nf_sodium": 100,
                "item_name": "Starbucks Vanilla Frappucino (Yield: 1 bottle)",
                "brand_name": "Gandolfo's New York Delicatessen",
                "nf_calories": 200,
                "item_type": 1
            },
            "sort": [
                200
            ]
        },
        {
            "_index": "4qnk4vry5gujjxptu5rg",
            "_type": "item",
            "_id": "513fc9c6673c4fbc26001dcc",
            "_score": null,
            "fields": {
                "nf_sodium": 95,
                "item_name": "Starbucks Mocha Frappuccino (Yield: 1 bottle)",
                "brand_name": "Gandolfo's New York Delicatessen",
                "nf_calories": 180,
                "item_type": 1
            },
            "sort": [
                180
            ]
        }
    ]
}

ToDo

add table of all acceptable attributes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment