Skip to content

Instantly share code, notes, and snippets.

@philschmid
Last active January 3, 2020 13:48
Show Gist options
  • Save philschmid/4db43d6f92728f15a2532464477c12c2 to your computer and use it in GitHub Desktop.
Save philschmid/4db43d6f92728f15a2532464477c12c2 to your computer and use it in GitHub Desktop.
Google Knowledge graph API --> typescript not tested. sollten aber nur ein paar kleine fehler sein.
const fetch = require('node-fetch')
key = 'xxxx'
const knowYourGraph = (apiKey, queryString, limit = 50, lng = 'en') => {
return new Promise(async (resolve, reject) => {
try {
// building Url for Knowledge Graph
const url = `https://kgsearch.googleapis.com/v1/entities:search?indent=true&languages=${lng}&limit=${limit}&query=${queryString}&key=${apiKey}`
// request API
console.log(url)
const response = await fetch(url, {
headers: {
Accept: 'application/json'
}
})
// response to js object
const json = await response.json()
// transform helper function
const returnValues = await transformEntities(json)
console.log(returnValues)
resolve(returnValues)
} catch (error) {
console.error(error)
reject(error)
}
})
}
async function transformEntities(inputEntitites) {
const entityListPromise =
inputEntitites && inputEntitites.itemListElement
? await inputEntitites.itemListElement.map(entity => {
const returnEntity = {
score: entity.resultScore,
name: entity.result.name,
type: entity.result['@type']
}
entity.result.description ? (returnEntity.description = entity.result.description) : null
entity.result.detailedDescription ? (returnEntity.detailedDescription = entity.result.detailedDescription) : null
entity.result.image ? (returnEntity.image = entity.result.image) : null
entity.result.url ? (returnEntity.url = entity.result.url) : null
return returnEntity
})
: new Error('nope')
return Promise.all(entityListPromise).then(function(promiseResults) {
// console.log(promiseResults);
return promiseResults
})
}
knowYourGraph(key, 'LG')
const fetch = require('node-fetch');
import {transformEntities} from './transformEntities.ts'
const knowYourGraph = (apiKey:string, queryString:string, limit = 50, lng = "en") => {
return new Promise(async (resolve, reject) => {
try {
// building Url for Knowledge Graph
const url:string = `https://kgsearch.googleapis.com/v1/entities:search?indent=true&languages=${lng}&limit=${limit}&query=${queryString}&key=${apiKey}`;
// request API
const response = await fetch(url, {
headers: {
Accept: "application/json"
}
});
// response to js object
const json = await response.json();
// transform helper function
const returnValues = await transformEntities(json)
resolve(returnValues);
} catch (error) {
console.error("Error:", error);
reject(error);
}
});
};
interface IRawEntity {
resultScore:number
"@type" :string
result: IEntityResult
}
interface IStructuredEntity {
score:number
type :string[]
name: string
description?:string
detailedDescription?: IDetailDescription
image?:IEntityImage
url?:string
}
interface IEntityResult {
description?:string
detailedDescription?: IDetailDescription
image?:IEntityImage
name:string
"@type" :string[]
url:string
}
interface IDetailDescription {
url:string
articleBody:string
license:string
}
interface IEntityImage {
url:string
contentUrl:string
}
export async function transformEntities(inputEntitites) {
const entityListPromise =
inputEntitites && inputEntitites.itemListElement
? await inputEntitites.itemListElement.map((entity:IRawEntity) => {
const returnEntity:IStructuredEntity = {
score: entity.resultScore,
name: entity.result.name,
type: entity.result['@type']
}
entity.result.description ? (returnEntity.description = entity.result.description) : null
entity.result.detailedDescription ? (returnEntity.detailedDescription = entity.result.detailedDescription) : null
entity.result.image ? (returnEntity.image = entity.result.image) : null
entity.result.url ? (returnEntity.url = entity.result.url) : null
return returnEntity
})
: new Error('nope')
return Promise.all(entityListPromise).then(function(promiseResults) {
// console.log(promiseResults);
return promiseResults
})
}
//transformEntities(event)
const event = {
'@context': {
kg: 'http://g.co/kg',
detailedDescription: 'goog:detailedDescription',
resultScore: 'goog:resultScore',
goog: 'http://schema.googleapis.com/',
EntitySearchResult: 'goog:EntitySearchResult',
'@vocab': 'http://schema.org/'
},
'@type': 'ItemList',
itemListElement: [
{
resultScore: 10029.216796875,
'@type': 'EntitySearchResult',
result: {
description: 'High-level programming language',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JavaScript',
articleBody:
'JavaScript, often abbreviated as JS, is a high-level, just-in-time compiled, object-oriented programming language that conforms to the ECMAScript specification. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/m/02p97',
image: {
url: 'https://commons.wikimedia.org/wiki/File:Unofficial_JavaScript_logo_2.svg',
contentUrl: 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT7KzxkEEx9wVcWhahN5XNbD0uZm4gRX6U6IL5Kvw97n90_Mfnz'
},
name: 'JavaScript',
'@type': ['Thing']
}
},
{
resultScore: 1095.615356445312,
'@type': 'EntitySearchResult',
result: {
'@id': 'kg:/m/019syg',
'@type': ['Thing'],
name: 'ECMAScript',
description: 'Programming language',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/ECMAScript',
articleBody:
'ECMAScript\nis a scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript to help foster multiple independent implementations. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
}
}
},
{
result: {
'@id': 'kg:/m/05cntt',
image: {
url: 'https://ko.m.wikipedia.org/wiki/%ED%8C%8C%EC%9D%BC:JSON_vector_logo.svg',
contentUrl: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTQF3g4iC8Wqozge5xLpogWUE6OnXg09rKWGcSEx9VIiW9_naxy'
},
name: 'JSON',
'@type': ['Thing'],
description: 'Programming language',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JSON',
articleBody:
'JavaScript Object Notation\nis an open-standard file format or data interchange format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
}
},
resultScore: 587.7177734375,
'@type': 'EntitySearchResult'
},
{
result: {
'@type': ['Book', 'Thing'],
name: 'JavaScript: The Good Parts',
description: 'Book by Douglas Crockford',
'@id': 'kg:/m/05j4_mq'
},
resultScore: 400.7242431640625,
'@type': 'EntitySearchResult'
},
{
resultScore: 372.74111938476562,
'@type': 'EntitySearchResult',
result: {
image: {
url: 'https://commons.wikimedia.org/wiki/File:AJAX_logo_by_gengns.svg',
contentUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcThv_ZgnYCfmVfT8PaiHnXiDQ7ENAwm342xL_YmFB7RGaPD1MQo'
},
'@type': ['Thing'],
name: 'Ajax',
detailedDescription: {
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License',
url: 'https://en.wikipedia.org/wiki/Ajax_(programming)',
articleBody:
'Ajax is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. '
},
'@id': 'kg:/m/05gj6g'
}
},
{
result: {
'@id': 'kg:/m/0fvx82',
'@type': ['Thing', 'SoftwareApplication'],
name: 'Prototype JavaScript Framework',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/Prototype_JavaScript_Framework',
articleBody:
'The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson in February 2005 as part of the foundation for Ajax support in Ruby on Rails. It is implemented as a single file of JavaScript code, usually named prototype.js. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
}
},
resultScore: 164.43186950683591,
'@type': 'EntitySearchResult'
},
{
resultScore: 136.60052490234381,
'@type': 'EntitySearchResult',
result: {
name: 'JavaScript library',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JavaScript_library',
articleBody:
'A JavaScript library is a library of pre-written JavaScript which allows for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies.',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/m/02q15wl',
'@type': ['Thing', 'SoftwareApplication']
}
},
{
'@type': 'EntitySearchResult',
result: {
'@type': ['Thing', 'SoftwareApplication'],
name: 'JavaScript framework',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JavaScript_framework',
articleBody:
'A JavaScript framework is an application framework written in JavaScript. It differs from a JavaScript library in its control flow: A library offers functions to be called by its parent code, whereas a framework defines the entire application design. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/g/11clygry2s'
},
resultScore: 134.81414794921881
},
{
'@type': 'EntitySearchResult',
result: {
'@id': 'kg:/m/0b1wj0',
'@type': ['Thing'],
name: 'JavaScript syntax',
description: 'Programming language',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JavaScript_syntax',
articleBody:
'The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.\nThe examples below make use of the log function of the console object present in most browsers for standard text output.\n',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
}
},
resultScore: 86.427818298339844
},
{
resultScore: 79.838554382324219,
'@type': 'EntitySearchResult',
result: {
image: {
url: 'https://ru.m.wikipedia.org/wiki/%D0%A4%D0%B0%D0%B9%D0%BB:V8_JavaScript_engine_logo_2.svg',
contentUrl: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRMHSe8wrCMU9Qci4k-PGNnTFz0dfGviMWA650bjXfPRP4aoiod'
},
'@type': ['Thing'],
name: 'JavaScript engine',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/JavaScript_engine',
articleBody:
'A JavaScript engine is a computer program that executes JavaScript code. The first JavaScript engines were mere interpreters, but all relevant modern engines utilize just-in-time compilation for improved performance.\n',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/m/05vmst'
}
},
{
resultScore: 31.52420806884766,
'@type': 'EntitySearchResult',
result: {
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/Chakra_(JavaScript_engine)',
articleBody:
'Chakra is a JavaScript engine developed by Microsoft for its Microsoft Edge web browser. It is a fork of the JScript engine used in Internet Explorer. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/g/11bw4t9n1w',
'@type': ['Thing', 'SoftwareApplication'],
name: 'Chakra'
}
},
{
resultScore: 7,
'@type': 'EntitySearchResult',
result: {
'@id': 'kg:/m/0cqmdf8',
'@type': ['Book', 'Thing'],
name: 'JavaScript'
}
},
{
resultScore: 7,
'@type': 'EntitySearchResult',
result: {
name: 'JAVASCRIPT',
'@id': 'kg:/g/11gjxs9zvs',
'@type': ['Thing']
}
},
{
resultScore: 7,
'@type': 'EntitySearchResult',
result: {
'@id': 'kg:/g/11j0q2_r3l',
'@type': ['Event', 'Thing'],
name: 'JavaScript'
}
},
{
result: {
'@type': ['Thing', 'SoftwareApplication'],
name: 'Mocha',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/Mocha_(JavaScript_framework)',
articleBody:
'Mocha is a JavaScript test framework for Node.js programs, featuring browser support, asynchronous testing, test coverage reports, and use of any assertion library.',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/m/011v61qm'
},
resultScore: 4.6730518341064453,
'@type': 'EntitySearchResult'
},
{
resultScore: 4.0994811058044434,
'@type': 'EntitySearchResult',
result: {
detailedDescription: {
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License',
url: 'https://en.wikipedia.org/wiki/Polymer_(library)',
articleBody:
'Polymer is an open-source JavaScript library for building web applications using Web Components. The library is being developed by Google developers and contributors on GitHub. '
},
'@id': 'kg:/g/11bw1gv9rg',
image: {
contentUrl: 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRuqvC0TdtMngVKCBwvFLMfBM8ULgwEFxXyQ4pcIM4TKi-Rw1kP',
url: 'https://en.wikipedia.org/wiki/Polymer_(library)'
},
'@type': ['Thing', 'SoftwareApplication'],
name: 'Polymer'
}
},
{
result: {
'@id': 'kg:/m/02hrpzc',
'@type': ['Book', 'Thing'],
name: 'JavaScript: The Definitive Guide',
description: 'Book by David Flanagan'
},
resultScore: 3.9245040416717529,
'@type': 'EntitySearchResult'
},
{
'@type': 'EntitySearchResult',
result: {
image: {
url: 'https://commons.wikimedia.org/wiki/File:Gmail_Icon.png',
contentUrl: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSoy8QW1LIhmLCSYxL7wyGh8UkDTz1zHGFiS0g17rdLdhwf7FCQ'
},
'@type': ['Thing', 'WebSite'],
name: 'Gmail',
detailedDescription: {
url: 'https://en.wikipedia.org/wiki/Gmail',
articleBody:
'Gmail is a free email service developed by Google. Users can access Gmail on the web and using third-party programs that synchronize email content through POP or IMAP protocols. ',
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License'
},
'@id': 'kg:/m/02q_bk'
},
resultScore: 2.61129093170166
},
{
resultScore: 1.51099956035614,
'@type': 'EntitySearchResult',
result: {
detailedDescription: {
license: 'https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License',
url: 'https://en.wikipedia.org/wiki/Google_Maps',
articleBody:
'Google Maps is a web mapping service developed by Google. It offers satellite imagery, aerial photography, street maps, 360° panoramic views of streets, real-time traffic conditions, and route planning for traveling by foot, car, bicycle and air, or public transportation.\n'
},
'@id': 'kg:/m/055t58',
image: {
url: 'https://commons.wikimedia.org/wiki/File:Google_Maps_icon.svg',
contentUrl: 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTepfDrf7-AqD_D0VNO_1bLll_ZlvFgcq9zMEwRY1cc2RAAXrzs'
},
name: 'Google Maps',
'@type': ['Thing', 'Brand', 'WebSite'],
description: 'Website'
}
},
{
result: {
'@id': 'kg:/g/11j486grkp',
'@type': ['Event', 'Thing'],
name: 'JavaScript 201: Intermediate Javascript'
},
resultScore: 1,
'@type': 'EntitySearchResult'
},
{
result: {
'@type': ['Event', 'Thing'],
name: 'Learn to Code Denver: JavaScript 101',
'@id': 'kg:/g/11j4lwd9s4'
},
resultScore: 1,
'@type': 'EntitySearchResult'
},
{
resultScore: 1,
'@type': 'EntitySearchResult',
result: {
'@type': ['Thing'],
name: 'Javascript',
'@id': 'kg:/g/11fjxfx8pp'
}
}
]
}
[
{
"score": 8437.1806640625,
"name": "Siemens Healthineers",
"type": ["Thing", "Organization", "Corporation"],
"description": "Healthcare company",
"detailedDescription": {
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
"url": "https://en.wikipedia.org/wiki/Siemens_Healthineers",
"articleBody": "Siemens Healthineers AG is the mother company for several medical technology companies and is headquartered in Erlangen, Germany. The company dates its early beginnings in 1847 to a small family business in Berlin, co-founded by Werner von Siemens. Siemens Healthineers is connected to the larger corporation, Siemens AG. The name Siemens Medical Solutions was adopted in 2001, and the change to Siemens Healthcare was made in 2008. In 2015, Siemens named Bernd Montag as its new global CEO. In May 2016, the business operations of Siemens Healthcare GmbH were rebranded \"Siemens Healthineers.\"\n"
},
"image": {
"contentUrl": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSLwI0dJk198LlCXAH-qttPJUfFF1B4qn49Gu1ex0pw02W6GOuz",
"url": "https://commons.wikimedia.org/wiki/File:Siemens_Healthineers_logo.svg"
}
},
{ "score": 107.2074966430664, "name": "Siemens Healthcare Pte. Ltd.", "type": ["Thing", "Organization", "Corporation"] },
{ "score": 72.09593963623047, "name": "Siemens Healthineers", "type": ["Thing", "Organization"] },
{ "score": 44.11040878295898, "name": "Siemens Healthineers Beteiligungen Gmbh & Co. Kg", "type": ["Thing", "Organization"] },
{ "score": 38.84961700439453, "name": "Siemens Healthineers Ltd.", "type": ["Thing", "Organization"] },
{ "score": 33.83473205566406, "name": "Siemens Healthcare, S.L.", "type": ["Thing", "Organization"] },
{ "score": 18, "name": "Siemens Healthcare S.A.S.", "type": ["Thing", "Organization"] },
{ "score": 15.2389965057373, "name": "Siemens Healthcare LLC", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Ltd", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers AG, Munich", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Diagnostics (Shanghai) Co., Ltd.", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Diagnostic Medical Devices Sales Intern", "type": ["Event", "Thing"] },
{ "score": 12, "name": "Siemens Healthineers, Inc.", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Holding III B. V.", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Beteiligungen Verwaltungs-GmbH", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Siemens Healthineers Ltd.", "type": ["Thing", "Organization"] },
{ "score": 12, "name": "Healthcare Leadership: Conversation with Vice President of Siemens Healthineers", "type": ["Thing", "Event"] },
{
"score": 6.058188438415527,
"name": "Siemens",
"type": ["Thing", "Organization", "Corporation"],
"description": "Automation company",
"detailedDescription": {
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
"url": "https://en.wikipedia.org/wiki/Siemens",
"articleBody": "Siemens AG is a German multinational conglomerate company headquartered in Munich and the largest industrial manufacturing company in Europe with branch offices abroad.\n"
},
"image": {
"contentUrl": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRbIwotiJH0_j_7DHSAQbLhMj2SRXbvJ8HgyKJzg2y0WvgsBrDl",
"url": "https://commons.wikimedia.org/wiki/File:Siemens_AG_logo.svg"
}
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment