How to implement Polymorphic objects in CouchDB / NoSQL? - nosql

I'd like to implement Polymorphic objects in a NoSQL / Document DB?
What is best practice?
Example:
Master Class
Item Object (All should have Item.Title, Item.Subtitle, Item.IconURL)
SubClasses: ItemPhoto, ItemPDF, ItemURL, ItemHTML
(Each subclass would have different properties)
I'd like to list all Items Generically - then get specific data when i drill down.
Possible Options:
Save a two different Documents -with Master/Child Type & ID
Save all as SubClass Documents with Internal Item Object
Other options??
Thanks

CouchDB stores documents (data), not classes (data with code). There's the code in map, validation, list, and show functions which handle documents, but those documents are plain objects that carry data only.
In your example, you can define a library function to check that a given document contains the data of an item, and then use this function to decide what to do. For example:
// in a "appTypes" library:
exports.isItem = function(doc) {
return doc.Title && doc.Subtitle && doc.IconURL;
}
// in a map function
function(doc) {
var appTypes = require('appTypes');
if (appTypes.isItem(doc)) {
// doc is an Item...
}
}
Obviously you can put all code belonging to an Item in an Item class and create instances of that class initialized with the data in the doc. But that's your choice, and does not change how CouchDB will handle the document.

Related

How to approach dynamically generated Firestore queries depending on nested user created Sub Collections?

/Countries/Lebanon/Governorates/Mount Lebanon/Districts/Chouf/Cities/Wadi al-Zayneh/Data/Products/Main Categories/Restaurants & Bakeries/Sub Categories/Snack/Sub Categories/Abo Arab Cafe
So as you can see, this is a snippet from my current Firestore structure. So many deeply nested collections. The issue is, I want to keep going deeper as long as a collection called 'Sub Categories' is found which in that case I would render them in the UI. And when eventually I reach a level where 'Sub Categories' is not found, I will render a different UI and show the actual products (The last document "Abo Arab Cafe" contains all the products as maps). The pattern of how many Sub Categories there are is unexpectable and can be modified by the end user.
How can I keep checking for Sub Categories? How to manage my queries in a way that they are dynamically generated at each level at the client-side?
I use Flutter. Here is my current queries structure:
import 'package:cloud_firestore/cloud_firestore.dart';
class FirebaseServices {
final FirebaseFirestore _db = FirebaseFirestore.instance;
CollectionReference mainCategoryCollectionReference() {
CollectionReference mainCategoryCollectionReference = _db.collection(
'/Countries/Lebanon/Governorates/Mount Lebanon/Districts/Chouf/Cities/Wadi al-Zayneh/Data/Products/Main Categories');
return mainCategoryCollectionReference;
}
CollectionReference subCategoryCollectionReference(
String parentSelectedCategory) {
CollectionReference mainCategoryCollectionReference = _db.collection(
'/Countries/Lebanon/Governorates/Mount Lebanon/Districts/Chouf/Cities/Wadi al-Zayneh/Data/Products/Main Categories/$parentSelectedCategory/Sub Categories');
return mainCategoryCollectionReference;
}
bool checkIfSubCategoriesExist(CollectionReference collectionReference) {
bool subCategoriesExist;
collectionReference.get().then((value) => {
subCategoriesExist = value.docs.isNotEmpty,
print('SubCategoriesExist: $subCategoriesExist')
});
return subCategoriesExist;
}
}
This works only if I know for certain how many levels of deepness there are, but since this can be modified by the user, it won't work.
Sorry for the very long question I had no idea how to explain it properly and clearly. Thank you in advance!
The structure is all wrong, there is no point in the structure being this deeply nested. The structure of the database needs to match what has to appear in the UI.
Assuming this is a worldwide application since you are using countries then you have to do the following:
Collection
Document
Fields
Countries
Random ID
countryName - arrayOfDistrict- arrayOfGovernorates
3 Fields under each document id, containing information about the country.
Then regarding Resturants:
Collection
Document
Fields
SubCollection
subCollectionId
Fields
Resturant
Random ID
resturant_name- resturant_location - info_about_resturant
Menu
randomId
dish_name - price -...
The problem with your db structure is that it is very nested instead of making a flat structure and that right now you are harcoding the whole path.
Using the above structure, you can create a dropdown with list of countries if the user chooses Lebanon, then you get the districts and the governorates. Then you can do a call to get the resturants that are inside each district, since in the documents inside Resturant collection you can get location of each resturant and name.
After that on click of each resturant, you will get the data inside the subcollection that will contain the full menu.
I think I found the solution with the help of a friend!
Since the checkIfSubCategoriesExist function is always checking on the very last reached level(using the collectionReference argument) whether Sub Categories exists or not, he suggested that in case it does exist, I can append to its argument collectionReference the new "Sub Categories" String to the path as a variable! This way I can query on it and voila!

Search for child items matching certain name values

This page describes how to retrieve an item, (immediate) child items and searching in Sitecore9 using the RESTful API (via PostMan).
What it doesn't appear to say is how to combine those queries.
I would like to search the children of an item which is specified by path. So, currently, I have this returning an item:
GET https://{{sitecorehost}}/sitecore/api/ssc/aggregate/content/Items('{{sitecorehome}}/banners-tests')?sc_apikey={{sitecore-master-apikey}}
I also have this returning the child items of that item:
GET https://{{sitecorehost}}/sitecore/api/ssc/aggregate/content/Items('{{sitecorehome}}/banners-tests/Subcontent/Image and Texts')/Children?sc_apikey={{sitecore-master-apikey}}
However, because the children are not immediate children - they are two levels down at /Subcontent/Image and Texts - I cannot request them. Yes, I could search for them, but then any items would come back with the matching criteria and I only want to search items under that particular path.
I would like something which, I imagine, would look something like this:
GET https://{{sitecorehost}}/sitecore/api/ssc/aggregate/content/Items?sc_apikey={{sitecore-master-apikey}}&$filter=Name eq 'banner' and Path eq 'banners-tests'
Or perhaps this:
GET https://{{sitecorehost}}/sitecore/api/ssc/aggregate/content/Items('{{sitecorehome}}/banners-tests')/Children?sc_apikey={{sitecore-master-apikey}}&$filter=Name eq 'banner'
But these do not work.
#Matt We can do filtering based on the item path. For example, considering item path as :
'sitecore/content/home/tenant1/Subcontent/Image and Texts/neededitem' - the one needed
'sitecore/content/home/tenant1/Subcontent/Image and
Texts/item1/neededitem/notneededitem' - the one we need to exclude
since '/' is not a valid character in the Sitecore item name and indicates the children of the needed item.
Hence, it can be used as a filter in javascript.
So we can split by 'Image and Texts' and then find the items.
For example, consider an array of results and let us say object with a collection of items is items and item path of each item is denoted by Path(let's say, this can be some other property as well) property
let items = [{
Path: 'sitecore/content/home/tenant1/Subcontent/Image and Texts/neededitem',
anotherProperty: 'text-val1'
}, {
Path: 'sitecore/content/home/tenant1/Subcontent/Image and Texts/item1/neededitem/notneededitem',
anotherProperty: 'text-val2'
}];
const results = items.filter(item => {
const splittedPath = item.Path.split('Image and Texts');
if (splittedPath[1].split("/").length <= 2) {
return item;
}
});
console.log(results);
In case your SSC controller (C#) is custom one and having access to Sitecore Context object or Sitecore APIs then the GetChildren() method of Item class will bring children of first level only.
I hope this helps.

graphql - Combining results from multiple resolvers into one

I have a set of functions at the server side which each return a list of objects of the same type based on the passed parameters to the resolvers in the GraphQL query-
query {
objListQuery {
objResolver1(params) {
obj-id
}
objResolver2(different params) {
obj-id
}
...
}
}
Here, objResolver1 and objResolver2 send back a list of obj objects.
Server side -
function objResolver1(params) -> returns list of obj
function objResolver2(different params) -> returns list of obj
...
I want to perform a logical AND between the results of the resolvers that is, find out the common objects in the results of the different resolvers.
Instead of getting the individual lists, I only want the combined list.
One way is to aggregate the results at the client side but this will increase the amount of duplicated data sent by the server.
What is the best way to achieve this at the server side? What changes are required in the schema?
--------------------EDIT--------------------
The data source is a JSON array of obj objects which is obtained from an external service at the server. Data source is not a database.
Parameters in each resolver can be one or many. It is used for filtering the objects. For example, the data store will have the structure as:
[
{"dateCreated":"2011-08-12T20:17:46.384Z",
"type":"customer",
....
},
{"dateCreated":"2011-08-14T20:17:46.384Z",
"type":"test",
....
}
]
resolvers will be of the form:
dateResolver(String startDate, String endDate) -> returns list of obj whose dateCreated is within the range
typeResolver(String[] type) -> returns list of obj whose type is anyone of the values passed in the array.
Assumed you're using a database you're somehow asking how to shift constraints from database- or repository-layer on controller-level.
While this has some weakness on model-level perhaps, it might depend on the class-implementation if you can easily change the objResolver in the kind that you just build one that allows more parameters like this:
query {
objListQuery {
objResolver(params1, params2, constraint) {
...
}
}
}
Like this you could create a database-query that is directly fetching the right result or you can perform several queries and resolve them inside the objResolver. If the constraint is always AND you could leave the parameter away, but perhaps you like to offer the possibility to use also OR, XOR, or others.
If the amount of parameter-sets is always 2, then it's simple like my code above, also considering the optional constraint. If the amount of parameter-sets might be variable, i.e. 4 or 5, then it's getting complicated if you still want to offer the constraint-parameter(s). Without constraint-parameter(s) it's simple, you just could note the function without parameters but check for the amount of parameters in the caller and handle them accordingly, in the caller you just use so many parameters as required.
query {
objListQuery {
objResolver() {
paramArray = getArguments();
}
}
}
Like written above it's getting hard, if you still want to offer constraint-parameters here, but I'd suggest that would be material for another question.
You can implement a Connection interface, with a single resolver to allow a one-step querying mechanism. You can reduce query endpoints using this technique.
E.g, an example query would look like:
allObjects(start: "01-01-2019", end: "04-29-2019", types:["test", "sales"]){
nodes {
id,
dateCreated,
type
}
}
In the resolver, you can use this criteria to prepare and return the data.
Benefits:
Less query endpoints.
Filtering and pagination.
Your filter interface can be quite fancy:
allObjects(
dateCreated: {
between:{
start,
end
},
skipWeekends: true
},
types: {
include:[],
exclude: []
}
)
Add new criteria as your needs grow. Start with what you want and take it from there.

Firestore query on collection

I have list of Collection IDs. Is there any way I can query and get all the documents under these collection ids? without iterating to each id in the list.
Thank you for your time
According to your last comment, I understand that you want to get all documents within a single collection and not to query multiple collections, which is not possbile for the moment in Firestore.
If you have a list of ids, then simply iterate over it and create for each id in the list the corresponding DocumentReference and then add all those references to a List<DocumentReference>. After that, iterate over the new list and for each reference create a Task and then add all those Tasks objects to List<Task<DocumentSnapshot>>.
In the end, just pass the list of Tasks to Tasks's whenAllSuccess() method:
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
#Override
public void onSuccess(List<Object> list) {
//Do what you need to do with your list
for (Object object : list) {
YourObject yb = ((DocumentSnapshot) object).toObject(YourObject.class);
Log.d("TAG", yb.getPropertyName);
}
}
});
In code it looks like my answer from this post:
Android Firestore convert array of document references to List<Pojo>

Querying in Firebase by child of child

I have a structure of objects in Firebase looking like this:
-KBP27k4iOTT2m873xSE
categories
Geography: true
Oceania: true
correctanswer: "Yaren (de facto)"
languages: "English"
question: "Nauru"
questiontype: "Text"
wronganswer1: "Majuro"
wronganswer2: "Mata-Utu"
wronganswer3: "Suva"
I'm trying to find objects by categories, so for instance I want all objects which has the category set to "Oceania".
I'm using Swift and I can't really seem to grasp the concept of how to query the data.
My query right now looks like this:
ref.queryEqualToValue("", childKey: "categories").queryOrderedByChild("Oceania")
Where ref is the reference to Firebase in that specific path.
However whatever I've tried I keep getting ALL data returned instead of the objects with category Oceania only.
My data is structured like this: baseurl/questions/
As you can see in the object example one question can have multiple categories added, so from what I've understood it's best to have a reference to the categories inside your objects.
I could change my structure to baseurl/questions/oceania/uniqueids/, but then I would get multiple entries covering the same data, but with different uniqueid, because the question would be present under both the categories oceania and geography.
By using the structure baseurl/questions/oceania/ and baseurl/questions/geography I could also just add unique ids under oceania and geography that points to a specific unique id inside baseurl/questions/uniqueids instead, but that would mean I'd have to keep track of a lot of references. Making a relations table so to speak.
I wonder if that's the way to go or? Should I restructure my data? The app isn't in production yet, so it's possible to restructure the data completely with no bigger consequences, other than I'd have to rewrite my code, that pushes data to Firebase.
Let me know, if all of this doesn't make sense and sorry for the wall of text :-)
Adding some additional code to Tim's answer for future reference.
Just use a deep query. The parent object key is not what is queried so it's 'ignored'. It doesn't matter whether it's a key generated by autoId or a dinosaur name - the query is on the child objects and the parent (key) is returned in snapshot.key.
Based on your Firebase structure, this will retrieve each child nodes where Oceania is true, one at a time:
let questionsRef = Firebase(url:"https://baseurl/questions")
questionsRef.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)
.observeEventType(.ChildAdded, withBlock: { snapshot in
print(snapshot)
})
Edit: A question came up about loading all of the values at once (.value) instead of one at at time (.childAdded)
let questionsRef = Firebase(url:"https://baseurl/questions")
questionsRef.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
})
Results in (my Firebase structure is a little different but you get the idea) uid_1 did not have Oceania = true so it was omitted from the query
results.
Snap (users) {
"uid_0" = {
categories = {
Oceania = 1;
};
email = "dude#thing.com";
"first_name" = Bill;
};
"uid_2" = {
categories = {
Oceania = 1;
};
"first_name" = Peter;
};
}
I think this should work:
ref.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)