Firebase Full-Text Search using Algolia - firebase

I configured different firebase functions by following this
. Now in this, there is firebase full-text search. I tried to follow it but it seems to be incomplete. I have searched and somehow got success in deploying. But it is still not creating index in Algolia. Can someone tell me the steps to correctly perform this?
I created the blog-posts and search nodes in my firebase project but problem is still there.
CODE:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Authenticate to Algolia Database.
// TODO: Make sure you configure the `algolia.app_id` and `algolia.api_key` Google Cloud environment variables.
const algoliasearch = require('algoliasearch');
const client = algoliasearch(functions.config().algolia.app_id, functions.config().algolia.api_key);
// Name fo the algolia index for Blog posts content.
const ALGOLIA_POSTS_INDEX_NAME = 'blogposts';
// Updates the search index when new blog entries are created or updated.
exports.indexentry = functions.database.ref('/blog-posts/{blogid}/text').onWrite(event => {
const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
const firebaseObject = {
text: event.data.val(),
objectID: event.params.blogid
};
return index.saveObject(firebaseObject).then(
() => event.data.adminRef.parent.child('last_index_timestamp').set(
Date.parse(event.timestamp)));
});
// Starts a search query whenever a query is requested (by adding one to the `/search/queries`
// element. Search results are then written under `/search/results`.
exports.searchentry = functions.database.ref('/search/queries/{queryid}').onWrite(event => {
const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
const query = event.data.val().query;
const key = event.data.key;
return index.search(query).then(content => {
const updates = {
'/search/last_query_timestamp': Date.parse(event.timestamp)
};
updates[`/search/results/${key}`] = content;
return admin.database().ref().update(updates);
});
});
SEE IMAGE OF FIREBASE NODE
Open Image
Your help will be appreciated. Thanks

So I used the sample code provided here and placed it into a Firebase cloud function. Writing to '/blog-posts/{blogid}/text' inside the database should index whatever value is under text to Algolia.
There are a few things that might be going wrong here:
Check that your function is correctly placed into Firebase. You can do this from the console by clicking functions on the left side. You should see two functions named indexentry and searchentry. If you do not see those functions then you haven't correctly pushed your code to the Firebase cloud.
If you code is in Firebase cloud then I recommend adding console.log("write on blog-posts fired"); to your searchentry function. Then write some more data to your database under '/blog-posts/{blogid}/text'. You can check the function log in the Firebase console. I have noticed a slight delay in log records displaying some times, so be patient if you don't see it right away. I'd write a few pieces of data to '/blog-posts/{blogid}/text' then after a couple minutes I'd check the log. If the log has "write on blog-posts fired" in it then you know the function is being activated when you write to the database.
If all the above is operating correctly and you still don't have any data in Algolia then make sure you set your API keys. You can do this using the code firebase functions:config:set algolia.app_id="myAlgoliaAppId" algolia.api_key="myAlgoliaApiKey". You run this command in a terminal window inside the directory where you have your Firebase cloud functions. You can get you API keys by signing into your account. Remember not to share your API key with anyone.

Related

Linking images from Firebase Storage to Firestore document and displaying them in React Native

Background
I'm trying to upload images to firebase storage manually (using the upload file button in the web page), however I have no clue how to later link them to a firestore document. What I have come up with (I'm unsure if it works) is copying the url for the image in the storage bucket and adding it to a string type field in the document called profilePicture. The reason I'm unable to get this to work is that I'm really new to React Native and I don't know how to properly require the images other than typing in the specific local route. Mind you also, the way I'm requiring user data such as a profile name is after logging in with email/password auth I pass the data as a param to react navigation and require it as extraData.
What I have tried
Once I've copied the image url and pasted it in the firestore document I'm doing this:
const profilePicture = props.extraData.profilePicture;
<Image source={require({profilePicture})}/>
I have also tried using backticks but that isn't working either. The error message I'm getting is:
TransformError src\screens\Profile\ProfileScreen.js: src\screens\Profile\ProfileScreen.js:Invalid call at line 27: require({
profilePicture: profilePicture
})
Note: this is an expo managed project.
Question
Is the problem in the code or in the way I'm linking both images? Maybe both? Should I require the document rather than relying on the data passed previously?
Thanks a lot in advance!
Edit 1:
I'm trying to get all info from the current user signed in, after a little research I've come to know about requiring images in this manner:
const ref = firebase.storage().ref('path/to/image.jpg');
const url = await ref.getDownloadURL();
and then I'd require the image as in <Image source={{uri: url}}/>
I get that this could be useful for something static, but I don't get how to update the ref for every single different user.
Edit 2:
Tried using the method mentioned in Edit 1, just to see what would happen, however It doesn't seem to work, the image just does not show up.
Maybe because my component is a function component rather than a class component (?
I understand that your goal is to generate, for each image that is uploaded to Cloud Storage, a Firestore document which contains a download URL.
If this is correct, one way is to use a Cloud Function that is triggered each time a new file is added to Cloud Storage. The following Cloud Function code does exactly that. You may adapt it to your exact requirements.
exports.generateFileURL = functions.storage.object().onFinalize(async object => {
try {
const bucket = admin.storage().bucket(object.bucket);
const file = bucket.file(object.name);
// You can check that the file is an image
const signedURLconfig = { action: 'read', expires: '08-12-2025' }; // Adapt as follows
const signedURLArray = await file.getSignedUrl(signedURLconfig);
const url = signedURLArray[0];
await admin.firestore().collection('profilePictures').add({ fileName: object.name, signedURL: url }) // Adapt the fields list as desired
return null;
} catch (error) {
console.log(error);
return null;
}
});
More info on the getSignedUrl() method of the Admin SDK here.
Also note that you could assign the Firestore document ID yourself, instead of having Firestore generating it as shown in the above code (with the add() method). For example, you can add to the image metadata the uid of the user and, in the Cloud Function,get this value and use this value as the Document ID.
Another possibility is to name the profile image with the user's uid.

firebase cloud function firestore not being triggered with region europe-west1

I am testing the new region settings for Firebase cloud functions something is not right (I may be doing something wrong).
Since our users are in europe i wanted to move all my project and my functions to europe.
Https functions are working as expected, just setting this:
export const test = region('europe-west1').https.onRequest(....)
On the other hand, I am having troubles with the firebase triggers. While this function works fine:
export const firebaseUpdateTrigger = region('us-central1')
.firestore
.document(...)
.onUpdate(...)
The same code just like this does not get triggered:
export const firebaseUpdateTrigger = region('europe-west1')
.firestore
.document(...)
.onUpdate(...)
What is it that I am doing wrong??
I am using these versions:
"firebase-functions": "2.0.4",
"firebase-admin": "5.13.1",
"#google-cloud/firestore": "^0.15.0"
You might have missed some of the required steps, to change a function's region, namely:
Rename the function, and change its region.
Deploy the renamed function, which results in temporarily running the same code in both regions.
Delete the previous function
You may gather more detail from the "Change a function's region" sub-chapter of the "Manage functions deployment and runtime options" online document.
Hey there #Borja Gorriz
I just had a similar issue, this one worked out for me:
exports.onTest2 = functions.region('europe-west2').firestore
.document('/mycollection/{documentID1}')
.onUpdate((change, context) => {
console.log('test all right');
});
Successful deployment:
after creating the function with same name I was getting the issue, that the event onCreate is not getting triggered. So, I deleted the old function (in old region) which I don't need. Then I deployed the again. It solved my problem.
deleted the old function
redeployed the new function

Firestore moving to timestamps in Firebase functions

Yesterday, all my firebase functions started throwing the following warning:
The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK. To hide this warning and ensure your app does
not break, you need to add the following code to your app before
calling any other Cloud Firestore methods:
const firestore = new Firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
With this change, timestamps stored in Cloud Firestore will be read
back as Firebase Timestamp objects instead of as system Date objects.
So you will also need to update code expecting a Date to instead
expect a Timestamp. For example:
// Old: const date = snapshot.get('created_at');
// New: const timestamp = snapshot.get('created_at'); const date =
timestamp.toDate();
Please audit all existing usages of Date when you enable the new
behavior. In a future release, the behavior will change to the new
behavior, so if you do not follow these steps, YOUR APP MAY BREAK.
Now I want to init my firestore correctly according to this warning. i'm using typescript.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
let fireStoreDB = fireStoreDB || admin.firestore()
the firestore() that return from admin doesn't have a .settings() method as described in the warning nor it gets an object in the constructor. (It gets an App Object).
so I have two questions:
How can init my firestore to get the settings object?
when I insert a date to a document or when I query a document do I also need to pass the Firestore.Timestamp object? or can i query/insert the normal JS Date object and it will get converted automatically?
Thanks.
EDIT:
i managed to solve it for http functions using :
if (!fireStoreDB){
fireStoreDB = admin.firestore();
fireStoreDB.settings(settings);
}
But it still is happening on firestore triggers.
anyone knows how to give default settings to admin on :
admin.initializeApp(functions.config().firebase);
so it will not happen on firestore triggers?
You are still receiving JS Date instead of Firestore Timestamp due to a bug... now fixed in Firebase Functions v2.0.2.
See: https://github.com/firebase/firebase-functions/releases/tag/v2.0.2.
For initialisation I've used admin.firestore().settings({timestampsInSnapshots: true}) as specified in warning message, so the warning has disappeared.
When you add a date to a Document, or use as a query parameter, you can use the normal JS Date object.
add below 2nd line code in your index.js firebase functions file
admin.initializeApp(functions.config().firebase);
admin.firestore().settings( { timestampsInSnapshots: true })
solved it the following way:
const settings = {timestampsInSnapshots: true};
if (!fireStoreDB){
fireStoreDB = admin.firestore();
fireStoreDB.settings(settings);
}
For firebase-admin version 7.0.0 or above
You should not be getting this error anymore.
In Version 7.0.0 - January 31, 2019 of firebase-admin there were some breaking changes introduced:
BREAKING: The timestampsInSnapshots default has changed to true.
The timestampsInSnapshots setting is now enabled by default so timestamp
fields read from a DocumentSnapshot will be returned as Timestamp objects
instead of Date. Any code expecting to receive a Date object must be
updated.
Note: As stated in the official docs, timestampsInSnapshots is going to be removed in a future release so make sure to remove it altogether.
For older versions of firebase-admin (6.5.1 and below)
This should do the work:
const admin = require('firebase-admin');
admin.initializeApp();
const firestore = admin.firestore();
// Add this magical line of code:
firestore.settings({ timestampsInSnapshots: true });
Then in your function use the firestore object directly:
firestore.doc(`/mycollection/${id}`).set({ it: 'works' })

How to update a document value with firebase cloud function

How can i update the value of a document on changing the value of another document.
I have raw-material document and finished-product document.
What i want to do is on changing the price of raw-material i want to update the price of finished-material
How can i do so ???
My code is like this so far
export const rawMaterialPriceChange = functions.database.ref('/raw-materials/{key}').onUpdate((snapshot)=>{
console.log('My key',snapshot.after.key);
var priceDiff = parseFloat(snapshot.after.val().price)-parseFloat(snapshot.before.val().price);
<HERE I WANT TO REFER ANOTHER DOCUMENT WITH SAME KEY AND UPDATE ITS VALUE
return true;
});
My firebase structure is like this:
Can anyone please help me ? Thank you
Found the solution from the following threads
Firebase HTTP Cloud Functions - Read database once
How to run query from inside of Cloud function?

basic firebase rules and search

Hi i'm trying to make a simple recipe react native app for school.
I am quit new to react native and noSQL. So how do i query in react native to my firebase?
what i want to do is to search for a specific product and to get all the recipes with this product in them. And the next thing i want to do is to be able to
add another product and find a recipe that has both of them and so on.
I have this setup for my firebase:
enter image description here
Note: For more complex queries I recommend using cloud functions.
On your question: With your data structured like that, it is impossible to achieve what you want using queries provided by firebase sdk. The problem is that your recipes have those ingredient1: 5505, ingredient2: 4404 ... change those to 5505: true, 4404: true. Then use the sdk like this:
const getRecipesForProduct = async (productName) => {
const product = await firebase.database().ref('products').orderByChild("name").equalTo(productName).once('value').then(snap => {...snap.val(), uid: snap.key()})
const recipes = await firebase.database().ref('recipe').orderByChild(product.uid).equalTo(true).once('value').then(snap => snap.val())
// do something with recipes
}

Resources