Monday 8 May 2017

Join query with ElasticSearch

I need to do a join query on firebase using elasticsearch, can anyone help me? In particular I have two nodes, in the child node I have a field that is the id of the father node and I would like to have as a result all the fields of the father node. How do I build my index in the code? In adding, in my client I use elasticsearchclient, here is an extract of the code to index a node:

var db = admin.database();
var etest = db.ref(type); 
etest.on('child_added',   createOrUpdateIndex);
etest.on('child_changed', createOrUpdateIndex);
etest.on('child_removed', removeIndex);

function createOrUpdateIndex(snap) {

 client.index(index, type, snap.val(), snap.key)
 .on('data', function(data) { console.log('indexed', snap.key + data ); })
 .on('error', function(err) { console.log('index error ', err); }).exec();
}

 function removeIndex(snap) {
  client.deleteDocument(index, type, snap.key, function(error, data) {
    if( error ) console.error('failed to delete', snap.key, error);
    else console.log('deleted', snap.key);
 });
}

And to take query results:

var queue = db.ref("search"); 
queue.child('request').on('child_added', processRequest);

function processRequest(snap) {
    console.log('process...... ');
   snap.ref.remove(); // clear the request after we receive it
   var data = snap.val();
   // Query ElasticSearch
    client.search(index, data.type, { "query": { 'query_string': {
            "query" : data.query
        }}})

   .on('data', function(results) {
       var res = JSON.parse(results);
       console.log(JSON.stringify(res.hits));
       console.log("TOTAL " + JSON.stringify(res.hits.total));
       queue.child('response/'+snap.key).set(results);
   })

   .on('error', function(error){ console.log("errore"); }).exec();

}

Thank you in advance



via matteo

No comments:

Post a Comment