Git Product home page Git Product logo

freebase.js's Introduction

Freebase is shutting down its APIs in May 2015. This library will not work past that date. Please plan ahead.


Freebase is a masculine but complicated human-curated database.

Nodejs is a straight-talkin language that takes no guff

Giddyup

npm install freebase

then:

var freebase= require('freebase');
freebase.description('tom cruise', {})
//"Tom Cruise, is an American film actor.."

Showin' off

All methods take the following form. The parameters are lazy.

freebase.method( "query",   {options},  callback()  )
freebase.method( "query",  callback()  )
freebase.method( "query",  {options}  )
freebase.method( "query" )

These methods return the same things:

freebase.image("/en/thom_yorke")
freebase.image("http://www.myspace.com/thomyorkemusic", {}, console.log)
freebase.image("thom yorke") //makes a 'decidedly safe guess'
freebase.image({"name":"thom yorke", "id":"/en/thom_yorke"}, console.log)

it's a good idea to include your api_key in each method:

freebase.sentence("meatloaf", {type:"/food/food", key:"MY_API_KEY"})

here are some options that you can ship in to any method:

{ nodeCallback: true, // use the 'error-first' callback form -> callback(error, result){}
  key: "MY_API_KEY", // good idea to include your freebase key, to avoid errors
  limit: 2, // truncate results
  debug: true, // print out the urls being fetched
}

You can also ship in any MQL parameters or search api parameters.

Video Demo

In the friggin browser

Demo - 63kb

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://rawgit.com/spencermountain/Freebase.js/master/client_side/freebase.min.js"></script>
<script>
  $(document).ready(function(){

    $.freebase.description("tony hawk", function (r){
      $('body').append(r)
    })

  })
</script>

In the shell:

the library can be run in the console, with the optional second parameter as the method. npm install it with a -g.

freebase george clooney
   # {  "mid": "/m/014zcr", "id": "/en/george_clooney" ... }
freebase sentence george clooney
   #"George Timothy Clooney is an American actor, film director, producer, and screenwriter."

Writing to Freebase:

####Oauth is hard, but you can do it. Instructions:

  • Register a project at [https://code.google.com/apis/console](google api console) and enable the Freebase API
  • In the 'Credentials' section, create a new Client ID -> 'installed application', 'other'
  • Add your data to './auth/credentials.js'
  • Run node ./auth/authenticate.js
  • You will be given a url to visit in your browser, which gives you an OAuth code.
  • Paste the oAuth code, and you'll be given the end tokens.

thats all you need to include in your request:

freebase.add_type("/en/the_who", {type:"/music/artist", token: your_access_token})

freebase.add_alias("/en/melanie_chisholm", {alias:"Sporty Spice", token: your_access_token})

You'll need to get a new token after about 3 hours. (Don't commit your credentials.)

If you're doing inference, or writing a bot, check out freebase_garden

Basic methods

####MQLread API MQL documentation

Books about planets:

var query=[{
  "type":  "/astronomy/planet",
  "name":  null,
  "/book/book_subject/works": []
 }]freebase.mqlread(query, {}, function(r){console.log(r)})

the options object will ship any paramaters to the freebase api.

####Pagination Every Tornado, ever

var query=[{
  "type":"/base/disaster2/tornado",
  "name":null
 }]
freebase.paginate(query, {max:400})

####Search API search api documentation

Hockey players named 'doug'

freebase.search("doug",{type: "/ice_hockey/hockey_player"})

the options object will ship any paramaters to the freebase search api.

####Description API First paragraph of a topic's wikipedia article:

freebase.description("mike myers", {})
freebase.description("http://myspace.com/u2", {})

####Topic API topic api documentation

A nicely treated output of all of a topic's data:

freebase.topic("mike myers", {})
freebase.topic("http://myspace.com/u2", {})

####RDF API RDF api documentation

A string of tuples for a topic:

freebase.rdf("blonde redhead", {})

####Notable-types The most accurate, or notable type for a topic:

freebase.notable("canada", {})
     -> {id:"/location/country", name:"Country"}

Sugar

####Grammar Which pronoun, tense, article and gender to use for this topic

freebase.grammar("washing machine", {})
   -> { plural: true,
        gender: null,
        article: 'a',
        pronoun: 'they',
        copula: 'are' }
freebase.grammar(["prince harry", "miranda july"], {})
   ->  [ { plural: false,
          gender: 'male',
          article: 'a',
          pronoun: 'he',
          copula: 'is' },
        { plural: false,
          gender: 'female',
          article: 'a',
          pronoun: 'she',
          copula: 'is' } ]

####Related Topics Similar topics to this topic

freebase.related("toronto", {}, function(r){
  console.log(r.map(function(v){return v.name}))
})
   /* Toronto FC
      Toronto Maple Leafs
      Toronto Argonauts
      North York
      Toronto Marlies*/

####Wordnet Query all of wordnet, from freebase:

freebase.wordnet("charming")
freebase.wordnet("submarine",{},console.log)

####SameAs links sameAs weblinks for a topic, or url

freebase.same_as_links("toronto")
freebase.same_as_links("http://toronto.ca", {}, console.log)

####Safe-Lookup A common-sense search that only matches when confident:

freebase.lookup("tom green")
freebase.lookup(["sandra bullock","suddenly susan"])

####First Sentence The first sentence from a wikipedia article:

freebase.sentence("kansas", {})
//"Kansas is a U.S. state located in the Midwestern United States."

####Graph-analysis Graph-type queries on topics, dancing over tough values and mediators:

freebase.outgoing("ubuntu", {} )
freebase.incoming("ubuntu", {} )
freebase.graph("ubuntu", {} )

####Schema-agnostic queries A list of topics in a 'is-a' type of collection:

freebase.list("earthquakes", {})

####Translation Translated names for topics:

freebase.translate("radiohead", {lang:"/lang/ko"})
  // "라디오헤드"

####Encoding Encode a string for inclusion in a freebase id/key/whatever

freebase.mql_encode("Aarno Yrjö-Koskinen")
  //"Aarno_Yrj$00F6-Koskinen"

####Schema introspection Find-out relevant information for a type or property:

freebase.property_introspection("politician", {})
   /* { domain: { name: 'Government', id: '/government' },
        is_compound_value: false,
        is_commons: 'Published',
        equivalent_topic: { name: 'Politician', id: '/en/politician' },
        topic_count: 90971,
        property_count: 0,
        included_types: [ { name: 'Person', id: '/people/person' },
                { name: 'Topic', id: '/common/topic' } ],
        ...*/

##Wikipedia

####Wikipedia-Category pages Get the wikipedia url for a topic

freebase.from_category("Category:Bridges_in_Saskatchewan", {
  depth: 2 //levels to recurse down
})
/*[{id: '/wikipedia/en/Long_Creek_Bridge',
   name: 'Long Creek Bridge'},
  {id: '/wikipedia/en/Diefenbaker_Bridge',
   name: 'Diefenbaker Bridge'}
   ...

####Wikipedia-page Get the wikipedia url for a topic

freebase.wikipedia_page("tony hawk", {})
 // http://en.wikipedia/wiki/Tony_Hawk

####Wikipedia categories Get the wikipedia categories on this topic's article

freebase.wikipedia_categories("tony hawk", {})

####Wikipedia topic-links Get the links on it's wikipedia page as freebase ids

freebase.wikipedia_links("tony hawk", {})
 /*[{ id: '/wikipedia/en/Baker_Skateboards',  name: 'Baker Skateboards' },
    { id: '/wikipedia/en/Bam_Margera', name: 'Bam Margera' },
    { id: '/wikipedia/en/Barting_Over', name: 'Barting Over' },
    { id: '/wikipedia/en/Blink-182', name: 'Blink-182' },
    ...*/

####Wikipedia external-links Get the external urls on it's wikipedia page

freebase.wikipedia_external_links("tony hawk", {})
   /*[{ url: 'http://skate.quiksilver.com/riders-detail/',
        domain: 'skate.quiksilver.com' },
      { url: 'http://skateboarding.transworld.net/1000095781/news/tony-hawk-on-theeve-trucks/',
        domain: 'skateboarding.transworld.net' },
        ...*/

##Geographical ####Geolocation Get the lat/lng for a topic

freebase.geolocation("calgary", {})
 //{ latitude: 51.0544444444, longitude: -114.066944444 }

####Nearby List topics near this geolocation

freebase.nearby("cn tower", {type:"/food/restaurant"})
   /*[{id: '/en/sneaky_dees',
       name: 'Sneaky Dee\'s',
      },
      {id: '/en/keg_mansion',
       name: 'Keg Mansion',
      }
      ...*/

####Inside List topics inside of this location

freebase.inside("montreal")
// [{"id": "/en/montreal_forum"}....]

####Place-data From a geo-coordinate, find out its City, Province, Country, and timezone

freebase.place_data({lat:51.545414293637286,lng:-0.07589578628540039}, console.log)

##Writing to freebase ###MQLWrite

  query=[{
    "id": "/en/radiohead",
    "type": [{
      "id": "/music/artist",
      "connect": "insert"
    }]
  }]
freebase.mqlwrite(query, {access_token: your_access_token})

###Add type sugar

freebase.add_type("/en/the_who", {type:"/music/artist", access_token: your_access_token})

###Add alias sugar

freebase.add_alias("/en/melanie_chisholm", {alias:"Sporty Spice", access_token: your_access_token})

##Method-list

  • mqlread -interface to freebase's mql api
  • search -regular search api
  • lookup -freebase search with filters to ensure only a confident, unambiguous result
  • lookup_id -generic info for an id
  • url_lookup -freebase search tuned for looking up a url
  • get_id -like freebase.lookup but satisfied with an id
  • topic -topic api
  • paginate -get all of the results to your query
  • wikipedia_page -get a url for wikipedia based on this topic
  • dbpedia_page -get a url for dbpedia based on this topic
  • mql_encode -quote a unicode string to turn it into a valid mql /type/key/value
  • rdf -RDF api
  • description -get a text blurb from freebase
  • image -get a url for image href of on this topic
  • notable -get a topic's notable type
  • drilldown -get insight into the breakdown of the topics in this type, by type and quality
  • property_introspection -common lookups for freebase property data
  • schema -common lookups for types and properties
  • grammar -get the proper pronoun to use for a topic eg. he/she/they/it
  • same_as_links -turns a url into a freebase topic and list its same:as links
  • translate -return specific language title for a topic
  • sentence -get the first sentence of a topic description
  • list -get a list of topics in a type
  • place_data -from a geo-coordinate and area radius (in feet), get the town, province, country, and timezone for it
  • is_a -get a list of identifiers for a topic
  • property_lookup -lookup soft property matches, like 'birthday' vs 'date of birth'
  • question -give a topic and a property, and get a list of results
  • wordnet -query wordnet via freebase
  • dig -transitive query on a specific property, maximum 3-ply
  • geolocation -lat/long for a topic
  • nearby -list of topics nearby a location
  • inside -list of topics inside a location
  • incoming -get any incoming data to this topic, ignoring cvt types
  • outgoing -return all outgoing links for a topic, traversing cvt types
  • graph -return all outgoing and incoming links for a topic
  • related -get similar topics to a topic
  • wikipedia_categories -get the wikipedia categories for a topic
  • wikipedia_links -outgoing links from this wikipedia page, converted to freebase ids
  • wikipedia_external_links -outgoing links from this wikipedia page, converted to freebase ids
  • from_category -get the freebase topics in a wikipedia category
  • wikipedia_subcategories -find the subcategories of this wikipedia category
  • wikipedia_to_freebase -turn a wikipedia title or url into a freebase topic
  • mqlwrite -write to freebase
  • add_type -add a type to a freebase topic
  • add_alias -add a alias to a freebase topic

##Examples

  • freebase.mqlread([{id:"/en/radiohead",name:null}])
  • freebase.lookup_id('/en/radiohead')
  • freebase.search("bill murray")
  • freebase.url_lookup("http://myspace.com/u2")
  • freebase.lookup("pulp fiction")
  • freebase.get_id("/en/radiohead")
  • freebase.topic("toronto", {filter:"allproperties"})
  • freebase.paginate([{"type":"/astronomy/moon","name":null, limit:2}],{max:13})
  • freebase.description("tunisia")
  • freebase.image('toronto',{type:"/location/citytown"})
  • freebase.grammar("toronto maple leafs")
  • freebase.same_as_links("toronto maple leafs")
  • freebase.translate("toronto maple leafs", {lang:"/lang/ja"})
  • freebase.notable("toronto maple leafs")
  • freebase.sentence('john malkovich',{},console.log)
  • freebase.list("hurricanes",{})
  • freebase.place_data({lat:51.545414293637286,lng:-0.07589578628540039}, {})
  • freebase.incoming("toronto")
  • freebase.outgoing("vancouver")
  • freebase.graph("shawshank redemption")
  • freebase.related("toronto", {})
  • freebase.is_a("george clooney")
  • freebase.property_lookup("albums")
  • freebase.question("keanu reeves", {property:"children"})
  • freebase.dig('/en/toronto', {property:'/location/location/contains'})
  • freebase.gallery('hurricanes')
  • freebase.wordnet("charming")
  • freebase.geolocation("cn tower")
  • freebase.nearby("cn tower", {type:"/location/location"})
  • freebase.inside("montreal")
  • freebase.wikipedia_page('toronto')
  • freebase.dbpedia_page('toronto')
  • freebase.wikipedia_categories("Tunisia")
  • freebase.wikipedia_links("Toronto", {})
  • freebase.wikipedia_external_links("Toronto", {})
  • freebase.property_introspection("/government/politician/party")
  • freebase.schema("politician")
  • freebase.drilldown("/chemistry/chemical_compound",{max:400})
  • freebase.from_category("Category:Bridges_in_Canada", {depth:2})
  • freebase.wikipedia_subcategories("Category:Enzymes",{depth:2}})
  • freebase.rdf("toronto")
  • freebase.documentation()

poo

Creative Commons, MIT

freebase.js's People

Contributors

spencermountain avatar trott avatar hangy avatar addisonj avatar

Stargazers

 avatar laserblue avatar  avatar Randy Amiel avatar Dumitru C. avatar Ashish avatar Angus H. avatar RYeah Sh avatar Prem Rose avatar Jin Liu avatar  avatar Steven avatar Michel Hiemstra avatar Pantelis Koukousoulas avatar Aleksandr Statciuk avatar Alfian Busyro avatar Andre Cassal avatar Youssef El Abbassi avatar Ed Wellbrook avatar Chris Hart avatar Moszeed avatar Aaron Signorelli avatar Tom Clarkson avatar Adam Hunt avatar Boris avatar Nam Chu Hoai avatar Ulrich Diedrichsen avatar Vincent Terrasi avatar  avatar Simon Hill avatar Tong avatar Chris Rolfs avatar Shmavon Gazanchyan avatar Rob Ellis avatar Eugen Sawin avatar Yotam Tanay avatar xavieramoros avatar Brian Jacobs avatar Tom Watson avatar Tim avatar Nick Barth avatar Charles E. Lehner avatar Ryan Ramage avatar Vishal Shah avatar Glavin Wiechert avatar Gael Gillard avatar Tom Stove avatar Julien Loutre avatar Sandro Pasquali avatar Fabiano avatar Yılmaz Uğurlu avatar Dani Acosta avatar Scott Anderson avatar Julia Jacobs avatar Scott Anderson avatar Nick Poorman avatar Petri Kola avatar Breck Yunits avatar Yunjia Li avatar Marcio Puga avatar Anders D. Johnson avatar Jim Lindstrom avatar  avatar Code avatar Bryan I. Smith avatar Pablo Casado avatar Marco Breiter avatar node-migrator-bot avatar Michael Bortnick avatar Ben Taylor avatar rosco5 avatar Michael Curry avatar David Hodge avatar DigitalLexicon avatar Mat Tyndall avatar Robin Ruaux avatar Christophe Desguez avatar  avatar ludo avatar Jeff Oh avatar Dan Thurman avatar Frederic Jacobs avatar  avatar Ryan Rose avatar Ian Webster avatar Alix Axel avatar Christian Nennemann avatar James Miller avatar Henry Kim avatar Joel Hughes avatar Todd Thille avatar Yasuhiro Inami avatar Julian Bilcke avatar clearbrian avatar Charles Cai avatar 3000 avatar  avatar Romain Ruetschi avatar Morgan Craft avatar Sumith Jitta avatar

Watchers

Rob Ellis avatar David H. Mason avatar  avatar AsO avatar ThomasWersinger avatar Andre Cassal avatar Code avatar  avatar James Cloos avatar Sinduja Ramaraj avatar l92 avatar Vincent Terrasi avatar Scott Anderson avatar  avatar

freebase.js's Issues

callback signatures

I'm experimenting with using Freebase.js in a Node.js project.

The Node.js convention for callbacks is to pass either null (if no error) or an Error object for the first parameter, and the data/result of that the user wants as the second parameter. Freebase.js doesn't do this. And in fact, the way it sends back errors appears to be different in different situations. (Or maybe it's not and I'm just confused. Regardless, I want to stick to convention.)

So, there are a few potential solutions for me. The absolute best would be for Freebase.js to switch to the convention. Would you be open to that? It appears that the Node.js callbacks happen in different places mostly than the web/client-side callbacks, so I think it's manageable. I could submit a pull request updating the code and inserting a line in the README saying "For Node.js, blah blah blah instead." But I don't want to do that if you'd be hesitant.

Broken!

npm http GET https://registry.npmjs.org/freebase
npm http 304 https://registry.npmjs.org/freebase
npm http GET https://registry.npmjs.org/freebase/-/freebase-2.1.23.tgz
npm http 404 https://registry.npmjs.org/freebase/-/freebase-2.1.23.tgz
npm ERR! fetch failed https://registry.npmjs.org/freebase/-/freebase-2.1.23.tgz
npm ERR! Error: 404 Not Found
npm ERR! at WriteStream. (/usr/local/Cellar/node/0.10.24/lib/node_modules/npm/lib/utils/fetch.js:57:12)
npm ERR! at WriteStream.EventEmitter.emit (events.js:117:20)
npm ERR! at fs.js:1596:14
npm ERR! at /usr/local/Cellar/node/0.10.24/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:103:5
npm ERR! at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this entire log,
npm ERR! including the npm and node versions, at:
npm ERR! http://github.com/isaacs/npm/issues

npm ERR! System Darwin 13.1.0
npm ERR! command "/usr/local/Cellar/node/0.10.24/bin/node" "/usr/local/bin/npm" "install" "freebase"
npm ERR! cwd /Users/codewarrior/dev/nodejs/projects/shift-exchange
npm ERR! node -v v0.10.24
npm ERR! npm -v 1.3.21
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/codewarrior/dev/nodejs/projects/shift-exchange/npm-debug.log
npm ERR! not ok code 0

Understanding search API matching logic in autocomplete use cases

Thanks for this module - very useful. I need to understand why the search API behaves a certain way. I'm using .search with no type key, to provide auto-complete functionality.

   freebase.search(term, {  key: nconf.get('google_api_key')}, function (result) { });

"social ident" matches nothing
"social identity" matches a bunch of things

In the autocomplete scenario, I need social ident to also match social identity. This is how the search box works on freebase.org.

Could you give me some pointers on why it behaves this way, and how to make it behave the way I want?

Yours gratefully.

Trouble installing the module

I'm having trouble installing the module.

npm ERR! Error: ENOENT, chmod '/Users/duncan/git/duncanmak/MovieCastAverageAge.ts/node_modules/freebase/lib/bin'
npm ERR! If you need help, you may report this log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR! [email protected]

npm ERR! System Darwin 12.2.0
npm ERR! command "/usr/local/Cellar/node/0.8.18/bin/node" "/usr/local/bin/npm" "install" "freebase"
npm ERR! cwd /Users/duncan/git/duncanmak/MovieCastAverageAge.ts
npm ERR! node -v v0.8.18
npm ERR! npm -v 1.2.2
npm ERR! path /Users/duncan/git/duncanmak/MovieCastAverageAge.ts/node_modules/freebase/lib/bin
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/duncan/git/duncanmak/MovieCastAverageAge.ts/npm-debug.log
npm ERR! not ok code 0

I googled around and it looks like some say running 'npm cache clean' should help, but I did and it didn't help.

Any suggestions?

Thanks!

Duncan.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.