Made a query in Watson discovery, tried to duplicate via nodejs sdk and the passages array is empty - watson-discovery

After doing a simple natural language query in the build query page, set the options for "include relevant passages to Yes. I get back 5 passages and results. All good. When I try from npm ibm-watson 6 nodejs sdk. I get the results, but an empty passages array with the same natural langauge text.
Here is the the url from the query page showing the options, which I tried all of them
https://api.us-east.discovery.watson.cloud.ibm.com/instances/d45df72b-93e4-4897-b9ac-98dc1e088afc/v1/environments/xx/collections/xx/query?version=2018-12-03&deduplicate=false&highlight=true&passages=true&passages.count=5&natural_language_query=what%20is%20autism
Here is the answer from the query builder page
Here is code example,
var discovery = new watson_discovery_v1({
authenticator : new IamAuthenticator({apikey: msg.startup.discovery_password}),
serviceUrl : msg.startup.discovery_endpoint,
version: '2020-09-22'
});
msg.WDSParams = {
environmentId: "x",
collectionId: "x",
passages: true,
count:5,
natural_language_query: msg.params.input.text
}
discovery.query(msg.WDSParams)
.then(results => {
msg.WDSResults = results; //your query results
node.send(msg);
})
.catch(err => {
console.log('error:', err);
});
Here is the json that came back from the discovery call
I have tried all of the passage options, duplicated the exact options that the query builder used. The same results come back, but no passages. Anyone have an idea? BTW using the Lite plan until I can prove passages works.

The problem was related to the way I called the query method. Below code resolved the issue. This code is for a nodeRed function node.
const watson_discovery_v1 = global.get('watson_discovery_v1');
const { IamAuthenticator } = global.get('ibm_auth');
const discovery = new watson_discovery_v1({
authenticator : new IamAuthenticator({apikey:
msg.startup.discovery_password}),
serviceUrl : msg.startup.discovery_endpoint,
version: '2019-04-30'
});
async function run() {
try {
const result = await discovery.query({
environmentId: 'x',
collectionId: 'x',
passages: true,
passagesCount: 2,
count: 5,
naturalLanguageQuery: msg.params.input.text
})
msg.WDSResults = result
clearTimeout(myTM)
}
catch(e){
node.error(e)
}
node.send(msg);
}
run()

Related

Gatsby 4 dynamic routes with Directus data seems imposible

I'm trying to create dynamic routing. Lets say we are building a blog.
The graphql data i get from Directus looks like this:
{
Directus {
Posts {
id
slug
Title
Body
}
}
}
and this seems to be a problem. No matter how i try to create the routes, Gatsby insists that the data structure should be with nodes instead of just an array. I have tried with the "File System Route API" which throws an error because of the missing nodes, the same thing happens if i try to define with "createPages" in gatsby-node.js.
Any help or suggestion is much appreciated...
I got it working... The solution is more simple then any guides i found on google, so here it comes, if anyone else ends up in the same situation.
Use the old cratePage method in a gatsby-node.js file, in root of project. I used this very simple code:
const path = require("path")
exports.createPages = async ({ graphql, actions }) => {
const { data } = await graphql(`
query Projects {
Directus {
Posts {
slug
}
}
}
`)
data.Directus.Posts.forEach(post => {
actions.createPage({
path: "/blog/" + post.slug,
component: path.resolve("./src/components/blog.js"),
context: { slug: post.slug },
})
})
}
And here's a link to useful information: https://www.youtube.com/watch?v=L32Vx_bEZhA

Strapi, use find to check if an object type field has a match in one of the properties

Let's say I have a field called user with a data that looks something like this
{
"id": "abc123",
"name": "John Smith"
}
I want to make a route where I can find where user.id equals, say, abc123 and should return the blogs that has a user with the id above
I've tried doing
async findByUser(ctx) {
let blogs = await strapi.services.blogs.find({
user: {id:ctx.params.id},
return blogs;
},
but that doesn't seem to work as it returns an empty array and isn't searching specifically in the id property. How do I do this using strapi?
edit: User is not an relation, it is an individual JSON field.
Okay, for querying a JSON object property, you will need to write a custom query. Look at the example below.
Implementation for PostGreSQL
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', '#>', `{"id": "${ctx.params.id}" }`);
// qb.where('user', '#>', `{"name": "${ctx.params.name}" }`);
})
.fetch();
return response.toJSON();
},
Implementation for SQLite
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetch();
return response.toJSON();
},
P.S: Just use fetch instead of fetchAll for consistency.
Hi there thanks to Salvino's help I think i am able to find a solution
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetchAll();
return response.toJSON();
},

Chat app list last messages of each peer using parse server

I am doing a chat app using parse server, everything is great but i tried make to list just last message for every remote peer. i didn't find any query limitation how to get just one message from every remote peer how can i make this ?
Query limitation with Parse SDK
To limit the number of object that you get from a query you use limit
Here is a little example:
const Messages = Parse.Object.extend("Messages");
const query = new Parse.Query(Messages);
query.descending("createdAt");
query.limit(1); // Get only one result
Get the first object of a query with Parse SDK
In you case as you really want only one result you can use Query.first.
Like Query.find the method Query.first make a query and will return only the first result of the Query
Here is an example:
const Messages = Parse.Object.extend("Messages");
const query = new Parse.Query(Messages);
query.descending("createdAt");
const message = await query.first();
I hope my answer help you 😊
If you want to do this using a single query, you will have to use aggregate:
https://docs.parseplatform.org/js/guide/#aggregate
Try something like this:
var query = new Parse.Query("Messages");
var pipeline = [
{ match: { local: '_User$' + userID } },
{ sort: { createdAt: 1 } },
{ group: { remote: '$remote', lastMessage: { $last: '$body' } } },
];
query.aggregate(pipeline)
.then(function(results) {
// results contains unique score values
})
.catch(function(error) {
// There was an error.
});

Can't find cache key in Cache redirect

When I start my react-native app I wan't to query "everything" for an offline experience.
So I
query all {
groups {
...GroupF
}
persons {
...PersonF
}
}${PERSON_ITEM}${GROUP_ITEM}
PersonF and GroupF are fragments.
The first view has a list of groups, each person can belong to a group. When the user clicks on an group the query looks like:
persons($group: ID) {
persons(group: $group) {
...PersonsF
}
}${PERSON_ITEM}
But my cacheRedirects just does not reflect the same data as is returned.
I know this because i console.log out the response in my component wrapper (it looks excellent here)
but in my
const cache = new InMemoryCache({
cacheRedirects: {
Query: {
persons: (_, args, {getCacheKeys}) => {
// I have tried everything here but nothing maps correctly
// I have tried getCacheKey({__typename: 'Person', id: args.group})
// I have tried following the apollo documentation
// No luck, it just can't find the group
// Using the chrome dev tools I don't see persons having groups
const a = getCacheKey({__typename: 'Person', id: args.group});
// Console.log(a) is:
// {generated: false, id: "Person:9", type: "id", typename "Person"}
}
}
}
});
Do you have any suggestions on how I can write a proper cache redirects persons query?
Help really really really appreciated
|1| https://www.apollographql.com/docs/react/advanced/caching.html#cacheRedirect
This was caused by the fact we used the id field in the Person, since we stoped using the field it works perfectly.

SuiteScript 2.0 Filter Operator AnyOf Not Working

I have a SuiteScript 2.0 that load and search transaction saved search with posting period filter. In my filter I am using 'anyof' operator which is not working for 'postingperiod' field
below is sample of my code:
function getTransactionData(datain)
{
try
{
var objSearch = search.load(
{
id: datain.savedsearchid
});
objSearch.filters.push(search.createFilter({ name: "postingperiod", operator: "ANYOF", values: ["42", "43"]}));
//above filter filters only record with internalid 42
result = readAllData(objSearch);
return result;
}
catch (ex)
{
log.error("getTransactionData", ex);
throw ex;
}
}
let me know if I am missing something here.
Please note above issue is occurring only for saved search, if I search other object for example 'account' object with internalid filter using 'anyof' operator, works fine.
Update: Today after more testing, found that its only happening for 'postingperiod' filter.
Try this code in Netsuite Debugger, Create a SavedSearch in Netsuite, don't add any filter in that , save that and get the id of saved search and use in below script against id value.
Also replace the Period Id with yours.
require(['N/runtime','N/search'],
function (runtime,search) {
var invoiceSearchObj = search.load({
type: "invoice",
id: '<your search id>',
columns:
[
search.createColumn({
name: "trandate",
sort: search.Sort.ASC,
label: "Date"
})
]
});
invoiceSearchObj.filters.push(search.createFilter({ name: "postingperiod", operator: "ANYOF", values: ["<your period value>"]}));
invoiceSearchObj.filters.push(search.createFilter({ name: "mainline", operator: "is", values : "T"}));
var searchResultCount = invoiceSearchObj.runPaged().count;
log.debug("invoiceSearchObj result count",searchResultCount);
invoiceSearchObj.run().each(function(result){
// .run().each has a limit of 4,000 results
return true;
});
});
var a=0;

Resources