How to get current member index in rs.conf() in MongoDB? - database

I am creating a Docker container with hidden secondary MongoDB instance for data backup purpose.
The only way to configure a MongoDB instance as a hidden secondary I found, is after its start by getting rs.conf() and setting the corresponding member values of votes, priority, and hidden. However, I cannot automatically figure out what is the cluster member index of my current instance in the members array. Any ideas?
This is the script that needs to be executed, where 2 should be replaced with the current member index.
cfg = rs.conf()
cfg.members[2].priority = 0
cfg.members[2].votes = 0
cfg.members[2].hidden = true
rs.reconfig(cfg)

Something like this maybe:
rso:PRIMARY> var myid=0;var x=0;var myself=db.isMaster().me ;rs.conf().members.forEach(function(d){ if(d.host==myself){ myid=x;print("The id is: "+myid)};x=x+1; })
The id is: 2
rso:PRIMARY> cfg.members[myid].priority=0
Explained:
Get the 'host:port' with the db.isMaster().me
Loop over all conf().members and search which one is me
Assign the myid to the member who is me.

Related

Finding in array of active record results

I am using active record to create array.
users = User.all.to_a
now I want to later on find with in this array user id: 1
users.find(1)
but it is not giving result but returning everything. How can I search in this result array my selected user id. I can see users is a an array but with in array each record of User object.
If I do following
user.first
it return User object, but I want to search, how can I do it. I understand if I remove to_a then it will work but then it will create another sql query.
Since it is an array of objects, you should use find with block:
users.find { |user| user.id == 1 }
User.find(1) is an ActiveRecord::FinderMethod. But when you already loaded all records into memory then those records are transformed into instances of User and stored in an Array. Therefore you need to use find or select which are implemented on Array like this:
users.find { |user| user.id == 1 } #=> returns the first found record
users.select { |user| user.id == 1 } #=> returns an array with all found record
Keep in mind that database queries are able to use efficient indexes when properly set up. Which makes database queries very fast. When you load all records into memory then those records need to be translated into proper instances. And searching on an array cannot use any index which means it could be (depending on the size of the array) slower than a new database query.

How to get the maximum number in DynamoDB column?

I have a DynamoDB table called URLArray that contains a list of URL's (myURL) and a unique video number (myNum).
I use AWS Amplify to query my table like so for example:
URLData = await API.graphql(graphqlOperation(getUrlArray, { id: "173883db-9ff1-4...."}));
Also myNum is a GSI, so i can also query the row using it, for example:
URLData = await API.graphql(graphqlOperation(getURLinfofromMyNum, { myNum: 5 }));
My question is, I would like to simply query this table to know what the maximum number of myNum is. So in this picture it'd return myNum = 12. How do i query my table to get this?
DynamoDb does not have the equivalent of the SQL expression select MAX(myNum), so you cannot do what you are asking with your table as-is.
A few suggestions:
Record the highest value of myNum as you insert items into the table. For example, you could create an item with PK = "METADATA" and an attribute named maxMyNum. The maxMyNum attribute could be updated conditionally if you have a value that is higher than what is stored in DDB.
You could build a secondary index with myNum as the sort key in a single partition. This would allow you to execute a query operation with ScanIndexForward set to false (descending order), and pick the first returned entry (the max value)
If you are generating an auto incrementing value in your application code, consider checking out the documentation regarding atomic counters.

MongoDB numeric index

I was wondering if it's possible to create a numeric count index where the first document would be 1 and as new documents are inserted the count would increase. If possible are you also able to apply it to documents imported via mongoimport? I have created and index via db.collection.createIndex( {index : 1} ) but it doesn't seem to be applying.
I would strongly recommend using ObjectId as your _id field. This has the benefit of being a good value for distributed systems, but also based on the date it was created. It also has a built-in index inside MongoDB.
Example using Morphia:
Date d = ...;
QueryImpl<MyClass> query = datastore.createQuery(MyClass);
query.field("_id").greaterThanOrEq(new ObjectId(d));
query.sort("_id");
query.limit(100);
List<MyClass> myDocs = query.asList();
This would fetch all documents created since date d in order of creation.
To load the next batch, change to:
query.field("_id").greaterThan(lastDoc.getId());
This will very efficiently load the next batch based on the ID of the last document from the previous batch.

Sitecore > Update commerce index incrementally

I am trying to rebuild commerce index in Sitecore incrementally(so, I don't want to make a full rebuild). Index strategy is set to "manual" at the moment.
I made some changes in catalog(updated relations and data, added/removed products and categories) and now just want to update index correspondingly.
I am tried to use class IndexCustodian(read about this class in the article). However, can't find the detailed documentation for this class with some code examples.
For example, I tried to use IncrementalUpdate method. As a second parameter I used an array of IndexableUniqueId(created on a search result using uniqueid field), but index hasn't been changed.
IEnumerable<IIndexableUniqueId> uniqueIds = foundProducts.Select(x => new IndexableUniqueId<string>(x.UniqueId));
Job job = IndexCustodian.IncrementalUpdate(ContentSearchManager.GetIndex(indexName), uniqueIds);
Another example, I tried to use Refresh method. As a second input parameter I used object of type CommerceIndexableItem which was created for the root sitecore item of my catalog. New products have been added, but existing product has been updated not completely: category relation has been updated, localized string field - hasn't been updated. Removed from catalog products still presented in the index.
Database database = Database.GetDatabase("web");
Item rootFolder = database.GetItem(Paths.DefaultCatalogPath);
CommerceIndexableItem indexableFolder = new CommerceIndexableItem(rootFolder);
Job job = IndexCustodian.Refresh(ContentSearchManager.GetIndex(indexName), indexableFolder);
Will appreciate any example of using of IndexCustodian or any other way which allows to update the index.
Thank you in advance for the help.

What will be the Query in my situation in Adobe CQ5

Root contains one folder, named pending of type sling:folder.
That have numbers of nodes of nt:unstructured type, having name of long value, that long value is very important for my code processing.
Now I want to get top 20 nodes(20 minimum node name , i.e., long value) data from this pending folder.
Can you tell me how can I write the JCR query for this situation ?
Edit No. 1
Repository repository = JcrUtils.getRepository("http://localhost:4502/crx/server");
Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
// Obtain the query manager for the session via the workspace ...
QueryManager queryManager = session.getWorkspace().getQueryManager();
// Create a query object ...
String expression = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([/pending])";
Query query = queryManager.createQuery(expression, javax.jcr.query.Query.JCR_SQL2);
// Execute the query and get the results ...
QueryResult result = query.execute();
// Iterate over the nodes in the results ...
NodeIterator nodeIter = result.getNodes();
But it gives some order , different than the order present in root node. But that is not in sort form.
Edit No.2
Now I got the functionality of this function. And it working fine now. The thing that I got is order the node just above the destination node, that is mentioned in second parameter of this function.
But the nodes that is coming is of different names(a number). So how can I sort this using orderBefore. Because everytime we are not able to know the right location(destination Relative Path) where we have to put this node.
You probably don't need a query for this, if you have structure such as
/pending/1
/pending/2
...
/pending/999
you can just iterate over the nodes using the JCR Node's getNodes() method, which returns a NodeIterator.
A sling:orderedFolder node type for "pending" gives a predictable ordering of the child nodes.
In general, using the tree structure instead of queries is more efficient in JCR.
Note also that if you're using Jackrabbit having more than about 10'000 child nodes on the same parent can lead to performance issues.

Resources