Algolia search for array that contains value - algolia

I am using Algolia search, and right now I use this to find a specific item by id:
algolia.getObject(id)
However, I need to make a search by barcode rather than ID - need a pointer in the right direction here.
The barcodes field is an array that can contain one or more barcode numbers.

You can trigger a search with filters on the barcodes attributes. The filters parameter supports multiple format, numeric values included. It does not matter if the attribute hold a single or multiple (an array) values. Here is an example with the JavaScript client:
const algoliasearch = require('algoliasearch');
const client = algoliasearch('YOUR_APP_ID', 'YOUR_API_KEY');
const index = client.initIndex('YOUR_INDEX_NAME');
index
.search({
filters: 'barcodes = YOUR_BARCODE_VALUE',
})
.then(response => {
console.log(response.hits);
});
The above example assumes that your records have a structure like this one:
{
"barcodes": [10, 20, 30]
}

Related

How to filter an array of object in Mui DataGrid?

I recently changed my tables to Mui-datagrid on Material UI 5, and I have a special use case with an array of objects. I want to enable the phone number filter in this column, but the number is provided as an object list.
phone: [
{ type: "home", number: "795-946-1806" },
{ type: "mobile", number: "850-781-8104" }
]
I was expecting a 'customFilterAndSearch' or an option to customise how to search in this specific field.
customFilterAndSearch: (term, rowData) =>
!!rowData?.suppressedOptions.find(({ description }) =>
description?.toLowerCase().includes(term.toLowerCase())
),
I have made some tries with the filterOperators, but no success yet. I have made a full example here https://codesandbox.io/s/mui-data-grid-vs05fr?file=/demo.js
As far as I can see from the DataGrid documentation I don't see any way to change the filter function for a specific function.
Likely the best workaround for your use case will be converting this to a string be converting the data to a string before you pass it to the datagrid. Though you will lose the styling that you currently do by making the phone type bold.
On second though your best best would probably be to split the phone column into two columns which would probably be the cleanest way of solving your problem
Add helper function.
You could potentially add a helper function to just map all the phone lists to something like mobilePhone or homePhone
const mapPhoneObject = (rows) => {
rows.forEach((row) => {
row.phone.forEach((phone) => {
row[`${phone.type}Phone`] = phone.number;
});
});
return rows
};
I've added a fork of your snippet with my function, it is I think the most viable solution for your problem: https://codesandbox.io/s/mui-data-grid-forked-ppii8y

Format response from mongoose into a model

How do you go about formatting the data response from mongoose? For a simple Post Schema
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
}
},{
timestamps: true
});
Whenever I do a GET request to find all the post, It returns me all its fields including _id and __v in which I wouldn't want to return those fields in an API.
Is there a way I would select only certain fields that I would want to return?
As far as I've found was that I could set a second parameter of title onto my query and it would return only the _id and title.
const post = await Post.find({},'title');
I find the method above isn't the proper way to filter fields in cases in the future where the values are deeply nested object and we would like to pick out certain values.
Is there perhaps a way to create a Model/Class and pick the fields based on the Model/Class and return the respond?
You can use select from mongoose.
You can either select only the fields you want.
var find = await model.find({}).select("my_field")
Or not show the fields you don't want
var find = await model.find({}).select("-my_field")
Check the documentation

Algolia : How to filter out a list of objectIDs client side

I have a list of users a user can follow, coming from the algolia index.
const index = client.initIndex('index');
const f= { filters: 'objectType:user };
index.search('user', f, (e, c) => {
const x = c.hits;
});
Now, there's an array of user IDs of users this user is already following, I don't want those users to be returned from this search, how do I filter those out. UserID is objectID in this case.
I recommend using Algolia's "Negative Filters" do achieve that.
https://www.algolia.com/doc/guides/searching/filtering/?language=instantsearchjs#negative-filters
So if you have an array of user ids, you could build a filter that looks like:
const filters = 'objectType:user AND NOT objectID:123 AND NOT objectID:456 ...';
You could build this filter string by looping through you array of ids, and adding this to your filter for each user id:
`AND NOT objectID:${userId}`

How do I prevent certain values from being returned in a search query?

How do I prevent certain values from being returned in a search query?
For example, I am using the geo-query feature of Algolia and would like to prevent the location from being sent back to the client?
I had a similar problem. I reached out to Algolia support and they suggested I delete whatever attributes I don't want indexed by deleting it after the objectID is obtained:
function addOrUpdateIndexRecord(contact) {
// Get Firebase object
const record = contact.val();
// Specify Algolia's objectID using the Firebase object key. ObjectID is obtained here
record.objectID = contact.key;
// Use this to delete the attributes you don't want indexed
delete record.whateverNameOfTheFirstAttribute
delete record.whateverNameOfTheSecondAttribute
delete record.whateverNameOfTheThirdAttribute
delete record.etcEtc
// Add or update object
index
.saveObject(record)
.then(() => {
console.log('Firebase object indexed in Algolia', record.objectID);
})
.catch(error => {
console.error('Error when indexing contact into Algolia', error);
process.exit(1);
});
}
}
You can specify Unretrievable Attributes: this features lets you select which information of your records should not be returned with your search results.
For example with the JavaScript API Client:
index.setSettings({
unretrievableAttributes: ["_geoloc"]
})

Send more than one term to algolia search

I'm implementing algolia search in my site and i want to get a set of data matching any id's i send to the search, so i need to know how could i send more than one parameter to the search, so i can send a set of ids, something like this:
let client = algoliasearch(APP_ID, API_KEY),
index = client.initIndex(INDEX_NAME);
let term=["3223212","2423434"];
index.search(term, callback)
This is not working right now, have any idea? or even how could i achieve my goal using another algolia feautre like filtering for instance?
If you're trying to retrieve objects by their objectIDs (which you can manually set at creation time to match your database ids), you can simply use the getObjects method.
Extract from the documentation:
You can also retrieve a set of objects:
index.getObjects(['myObj1', 'myObj2'], function(err, content) {
console.log(content);
});
If you're trying to list all the records that belong to a group with a specific id, you can use a facet that will contain this id and filter on it.
Inside your record:
{
"group_id": "3223212",
// or
"group_ids": ["3223212", "2423434"]
}
Inside your index settings:
{
attributesForFaceting: [
'onlyFilter(group_id)'
]
}
At query time:
let ids = ["3223212", "2423434"];
let filters = ids.map(id => `group_id:${id}`).join(' OR ');
index.search('', { filters: filters }, callback);