简体   繁体   中英

Algolia Instant Search Firebase Cloud Function - how to get the other value?

I don't have much idea about JavaScript, so I used Algolia's Instant Search for Firebase Github Repository to build my own function.

My function:

exports.indexentry = functions.database.ref('/posts/{postid}/text').onWrite(event => {
  const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
  const firebaseObject = {
    text: event.data.val(),
   timestamp: event.data.val(),
    objectID: event.params.postid
  };

In Algolia indices, with timestamp as the key, I get the same value as in text field, but in Firebase backend timestamp is different. How to fix this?

I tried different statements to get timestamp value but couldn't.

Edit

Expected Outcome :

{
    text: "random rext",
    timestamp: "time stamp string",
    author: "author name",
    object ID: "object ID"
}

Actual Outcome

{
    text: "entered text",
    object ID: "object ID"
}

EDIT 2: Answer can be found here .

Original Answer: What Bob Snyder said about the timestamp event is correct.

There may be other fields as well, for example, author_name that we may need to index, is there a generalized way to do that or do I write separate functions for every field?

If you want a general way to add all fields, I think what you are looking for can be found here . This should give you the right guidance to get what you want, ie save your whole object into the Algolia index.

EDIT:

index.saveObject(firebaseObject, function(err, content) {
    if (err) {
      throw err;
    }
    console.log('Firebase object indexed in Algolia', firebaseObject.objectID);
  });

I'm not real clear about your goal. Event has a timestamp property. Have you tried:

  const firebaseObject = {
    text: event.data.val(),
    timestamp: event.timestamp, // <= CHANGED
    objectID: event.params.postid
  };

If you want a long instead of string , use Date.parse(event.timestamp)

event.data.val() returns the entire firebase snapshot. If you want a specific value in your data you add it after .val() for example if every post has an author stored in your firebase database under they key "author" you can get this value using var postAuthor = event.data.val().author

I've included some samples from my code for those interested. A sample post looks like this: 在此处输入图片说明

Then inside my cloud functions I can access data like this:

const postToCopy = event.data.val(); // entire post
const table = event.data.val().group;
const category = event.data.val().category;
const region = event.data.val().region;
const postKey = event.data.val().postID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM