export results of MarkLogic query (mlcp, xdmp.save) - export

I have a simple query that filter documents based on the value of a property and return their results.
eg :
var query = 'Yes'
const jsearch = require('/MarkLogic/jsearch');
const myPaths = { paths: ['/envelope/instance/entity'] };
result = jsearch.documents()
.where(jsearch.byExample({ property: query }))
.map({ extract: myPaths })
.result();
Is it possible to use MLCP or a MarkLogic API to save the results of this query as JSON? Compressed results?
Based on this documentation https://docs.marklogic.com/guide/mlcp/export#id_47556 it is possible to do so. But I don't know how to serialize a query that uses jsearch instead of cts.

You need to first extract jsearch query and serialise it as -query_filter option.
Then you combine -query_filter and -document_selector option to export the specified node.
The mlcp options_file translation of your jsearch query is:
export
-mode
local
-host
localhost
-port
***
-username
***
-password
***
-output_file_path
***
-document_selector
{path-expression}
-query_filter
{"jsonPropertyValueQuery":{"property":["property"], "value":["Yes"]}}

Related

Send 2 identical Graphql queries in one call but with different variables

I have a search query which takes an variable and searches based on that.
On my home page I'd like to send this query 3 times with 3 different variables.
But if I do as above I can't get the results.
Here is the query:
const TOP_TEACHER_QUERY= gql`
query topTeachers {
searchBasicTeachersByRating(rating: 3) {
id
name
title
}
searchBasicTeachersByRating(rating: 4) {
id
name
title
isNew
}
}
}
and this is the function
allQueries() {
return this.apollo
.watchQuery<any>({
query: TOP_TEACHER_QUERY,
})
.valueChanges;
}
NOTE :
I have tried adding an interface and define the desired response data, but it has no effect
interface Response {
searchBasicTeachersByRatingMedium: Student[];
searchBasicTeachersByRatingHigh: Student[];
}
allQueries() {
return this.apollo
.watchQuery<any>({
query: TOP_TEACHER_QUERY,
})
.valueChanges;
}
THE DATA IS ONLY CONTAINING A LIST NAMED AFTER THE QUERY (searchBasicTeachersByRating)
I have tried the following query in graphql playground and it returns 2 arrays
but in Angular I can only get one
As a work around I created new queries at back-end, or sent 2 different queries.
But I want a solution for this approach.
Thanks in advance
When a selection set includes the same field multiple times, you need to utilize aliases for the duplicate fields:
searchBasicTeachersByRatingMedium: searchBasicTeachersByRating(rating: 3) {
id
name
title
}
searchBasicTeachersByRatingHigh: searchBasicTeachersByRating(rating: 4) {
id
name
title
isNew
}
After the request completes, each field will be available as a property on data under the provided alias. In the example above, we aliased both fields, but you could omit the alias from one of them.

Issue with .populate() on array of arrays in Mongoose Model [duplicate]

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
which gives me the expected result and queries.
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
you can also do something like below:
{path:'user',select:['key1','key2']}
You achieve that by simply passing object or array of objects to populate() method.
const query = [
{
path:'books',
select:'title pages'
},
{
path:'movie',
select:'director'
}
];
const result = await Person.find().populate(query).lean();
Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!
This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html
Let's say you have a BookCollection schema which contains users and books
In order to perform a query and get all the BookCollections with its related users and books you would do this
models.BookCollection
.find({})
.populate('user')
.populate('books')
.lean()
.exec(function (err, bookcollection) {
if (err) return console.error(err);
try {
mongoose.connection.close();
res.render('viewbookcollection', { content: bookcollection});
} catch (e) {
console.log("errror getting bookcollection"+e);
}
//Your Schema must include path
let createdData =Person.create(dataYouWant)
await createdData.populate([{path:'books', select:'title pages'},{path:'movie', select:'director'}])

Ordering the solr search results based on the indexed fields

I have to order the search results from solr based on some fields which are already indexed.
My current api request is like this without sorting.
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19
And it gives the search results based on the indexed order. But I have to reorder this results based on the filed 'last_login' which is already indexed DateTimeField.
Here is my viewset
class ProfileSearchView(FacetMixin, HaystackViewSet):
index_models = [Profile]
serializer_class = ProfileSearchSerializer
pagination_class = PageNumberPagination
facet_serializer_class = ProfileFacetSerializer
filter_backends = [HaystackFilter]
facet_filter_backends = [HaystackFilter, HaystackFacetFilter]
def get_queryset(self, index_models=None):
if not index_models:
index_models = []
queryset = super(ProfileSearchView, self).get_queryset(index_models)
queryset = queryset.order_by('-created_at')
return queryset`
Here I have changed the default search order by 'created_at' value. But for the next request I have order based on the 'last_login' value. I have added a new parameter in my request like this
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19&sort='last_login'
but it gives me an error
SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field sort]
How can I achieve this ordering possible? Please help me with a solution.
The URL you provided http://127.0.0.1:8000/api/v1/search/facets/ is not direct SOLR URL. It must be your middle-ware. Since you have tried the query directly against Solr and it works, the problem must be somewhere in middle-ware layer.
Try to print or monitor or check logs to see what URL the midde-ware actually generates and compare it to the valid URL you know works.

Visualforce RemoteObjectModels Query filtering using "OR"

I am using in visualforce page of Salesforce.com. For demo purposes, I have used the following code snippet from the example docs shown in
http://docs.releasenotes.salesforce.com/en-us/spring14/release-notes/rn_vf_remote_objects.htm
In my code snippet i have a 'Where' clause in which i am trying to filter using 3 fields. My requirement is that the records must match the criteria A or criteria B or criteria C.
Code Example
<apex:page >
<!-- Remote Objects definition to set accessible sObjects and fields -->
<apex:remoteObjects >
<apex:remoteObjectModel name="Group_Donor__c" jsShorthand="Groupdonor"
fields="Name,Id">
<apex:remoteObjectField name="State__c" jsShorthand="State"/>
<apex:remoteObjectField name="Org_Phone__c" jsShorthand="Phone"/>
<apex:remoteObjectField name="Billing_Type__c" jsShorthand="billingtype"/>
</apex:remoteObjectModel>
</apex:remoteObjects>
<!-- JavaScript to make Remote Objects calls -->
<script>
var fetchWarehouses = function(){
// Create a new Remote Object
var wh = new SObjectModel.Groupdonor();
// Use the Remote Object to query for 10 warehouse records
wh.retrieve({
where: {
or: {
Name : {like:"%Helloworld%"}, // Error
State: {like:"%chennai%"},
//Phone: {like:"%098765432344%"},
billingtype: {like:"%Credit Card%"}
}
},
limit: 10 ,
}, function(err, records, event){
if(err) {
alert(err.message);
}
else {
var ul = document.getElementById("warehousesList");
records.forEach(function(record) {
// Build the text for a warehouse line item
var whText = record.get("Name");
whText += " -- ";
whText += record.get("Phone");
whText += " -- ";
whText += record.get("billingtype");
// Add the line item to the warehouses list
var li = document.createElement("li");
li.appendChild(document.createTextNode(whText));
ul.appendChild(li);
});
}
});
};
</script>
<h1>Retrieve Group Donors via Remote Objects</h1>
<p>Warehouses:</p>
<ul id="warehousesList">
</ul>
<button onclick="fetchWarehouses()">Retrieve Group Donors</button>
</apex:page>
When i execute this code i get the following error.
Error Message :
Invalid criteria specified for retreival. ValidationError [code=11, message=Data does not match any schemas from "oneOf" path=/where, schemaKey=null]
This issue occurs only during the following conditions.
When i use Standard field like Name in the OR condition. ( Even 2 or 1 filter)
When i use more than 3 Custom fields in the OR condition ( More than 2 Query filter)
But when i use just any 2 custom fields mentioned in the RemoteObjectModel as filters, i get the expected results.
Kindly let me know what am i missing here. If i have use more than 2 filters in or condition, how do i achieve it ? is the usage of 'OR' proper in the remote-objects?. And has anyone come across this issue. if so kindly provide me some pointers.
Thanks in advance.
I've been doing some looking and there's some bad news and some good news.
First, it's a (obscure)known limitation that you can't have more than 2 predicates for AND and OR queries - Docs here
However, you seem to have discovered another bug in that an Standard Field (Name, Id) seems to not work when used with a custom one. My workaround was to redefine ALL fields, even standard ones like this:
<apex:remoteObjectModel name="Group_Donor__c" jsShorthand="GroupDonor">
<apex:remoteObjectField name="Name" jsShorthand="NameJS"/>
<apex:remoteObjectField name="State__c" jsShorthand="State"/>
<apex:remoteObjectField name="Org_Phone__c" jsShorthand="Phone"/>
<!--.... etc-->
At least you'll be able to query standard fields this way.
As an ultimate work around, you'll probably have to retrieve two lists of records and use JavaScript to create your ultimate OR list.
Good luck!

Spring Data MongoDB - Criteria API OrOperator is not working properly

I'm facing Spring Data MongoDB Criteria API orOperator problem.
Here's query result for irregular verbs: (Terminal output)
> db.verb.find({'v2':'wrote'});
{ "_id" : ObjectId("5161a8adba8c6390849da453"), "v1" : "write", "v2" : "wrote", "v3" : "written" }
And I query verbs by their v1 or v2 values using Spring Data MongoDB Criteria API:
Criteria criteriaV1 = Criteria.where("v1").is(verb);
Criteria criteriaV2 = Criteria.where("v2").is(verb);
Query query = new Query(criteriaV1.orOperator(criteriaV2));
List<Verb> verbList = mongoTemplate.find(query, Verb.class)
But unfortunately verbList doesn't have any item.
As far as I remember in order to use orOperator you should do:
Query query = new Query(new Criteria().orOperator(criteriaV1,criteriaV2));
We need explicitly specify a new criteria with OR condition - try with below example
Criteria criteria = Criteria.where("field1").is(val1).
.andOperator(new Criteria().orOperator(Criteria.where("field2").is(filterVal),
Criteria.where("field3").is(filterVal)));

Resources