FoodKG is a comprehensive food knowledge graph that consolidates information from diverse food-related data sources. It includes recipes, nutrition data, and ingredient information, all linked into a unified ontology with provenance maintained for each data point.
To interact with FoodKG, use the following public SPARQL endpoint:
https://inciteprojects.idea.rpi.edu/foodkg
You must use SPARQL to extract the FoodKG triples.
SPARQL (SPARQL Protocol and RDF Query Language) is specifically designed for retrieving and manipulating data stored in RDF (Resource Description Framework) format. It is similar to SQL but is used for querying graph-based data structures rather than relational databases. In SPARQL, data is represented as a graph of triples (subject-predicate-object).
To help you get started, here are some beginner-friendly and advanced tutorials that cover the basics and advanced features of SPARQL:
PREFIX recipe-kg: <http://idea.rpi.edu/heals/kb/>
SELECT ?recipe
WHERE {
?recipe rdfs:label "Vegetable Soup" .
}
LIMIT 5
To count the number of ingredients for each recipe, you can use the COUNT function along with GROUP BY to group the results by each recipe. Here’s how to modify the query:
PREFIX recipe-kg: <http://idea.rpi.edu/heals/kb/>
SELECT ?recipe (COUNT(?ingredient) AS ?ingredientCount)
WHERE {
?recipe rdfs:label "Vegetable Soup";
recipe-kg:uses ?ingredient.
}
GROUP BY ?recipe
Below are some useful Python code snippets for querying FoodKG using SPARQL.
To interact with FoodKG using Python, you need to install the SPARQLWrapper
library. You can install it by running:
pip install SPARQLWrapper
from SPARQLWrapper import SPARQLWrapper, JSON
from pprint import pprint
# Initialize the FoodKG endpoint
sparql = SPARQLWrapper("https://inciteprojects.idea.rpi.edu/foodkg/namespace/kb")
def fetch_recipes():
query = '''
PREFIX recipe-kg: <http://idea.rpi.edu/heals/kb/>
SELECT ?recipe
WHERE {
?recipe rdfs:label "Vegetable Soup" .
}
LIMIT 5'''
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
recipe = [x['recipe']['value'] for x in results['results']['bindings']]
return recipes
# Example usage
recipes = fetch_recipes()
pprint(recipes)