Looking for a simple text Template Engine to generate Query - javascript

I am using couchbase which has a feature called N1QL which is similar to SQl but for couchbase doc store. My problem is that if i want to query by several fields i have to create a template for each possible option which can get out of hand.
Before i take a stab at building my own template based system i was wondering if there is a basic text template engine which supports stuff like if and ets me pass values.
This is part of a sample query
FROM Contacts AS f
LEFT JOIN Contacts AS t
ON t._type ="tract_info" AND ANY b IN t.tract_id SATISFIES b = f.tract END
WHERE f._type="farm" and f.tract IN $3 $4
order by f.PropertyAddress.streetName, TONUMBER(f.PropertyAddress.houseNumber)
where i would like to pass something like {25,0,(12,25,35),“and ARRAY_COUNT(f.phones) > 0 and ARRAY_COUNT(f.emails) > 0”}
Any idea or pointesr would be great

The SDK already has a way to construct queries programmatically. You can see an example of this in the demo app, here:
https://github.com/couchbaselabs/try-cb-java/blob/5.0-updates/src/main/java/trycb/service/Airport.java#L36
This is Java code, of course. But the JS SDK should have something similar.

Related

Looping through a list of Java objects in JavaScript with Thymeleaf

In a Spring Boot project, I have a list of users, in Java List<User>
I pass it from the Controller to the template, I am able to loop through this list using a HTML list ul but I am not able to do it in JavaScript:
<script layout:fragment="script" th:inline="javascript">
/*<![CDATA[*/
var users = /*[[${users}]]*/ [];
for (var i = 0; i < users.length; i++) {
console.log(i); // Obviously here I would like to access the User properties
}
/*]]>*/
</script>
I get this error:
Error during execution of processor
'org.thymeleaf.standard.processor.text.StandardTextInliningTextProcessor'
How do we loop through lists and access Java object properties in JavaScript with Thymeleaf?
Thanks.
EDIT: what I have discovered so far
My User class is a JPA entity with a Country property (Country is another JPA entity):
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "country_id")
private Country country;
If I pass a list of users without the country fetched the JavaScript works.
If I pass a list of countries and loop through (to test the Country class by itself), it works too.
If I pass a list of users where I set the country myself (not fetched from database) with the same values as the database contains, it works
If I retrieve the country from the database, then set it to the user, it fails.
So it seems like the problem is because the Country entity is created/mapped to the User a certain way by Spring Data/Hibernate that Thymeleaf can not deserialize it...
JavaScript natural templates
Have you got Jackson library in your classpath?
If you have it, It should work.
If you take a look the reference documentation it works as you are doing it:
An important thing to note regarding JavaScript inlining is that this
expression evaluation is intelligent and not limited to Strings.
Thymeleaf will correctly write in JavaScript syntax the following
kinds of objects:
Strings ...
That ${session.user} expression will evaluate to a User object, and Thymeleaf will correctly convert it to Javascript syntax
At least, other way If you want, is configure how the Serialization is done with an instance of StandardDialect:
The way this JavaScript serialization is done is by means of an
implementation of the
org.thymeleaf.standard.serializer.IStandardJavaScriptSerializer
interface, which can be configured at the instance of the
StandardDialect being used at the template engine.
As I've said before, you should have Jackson Library in your classpath (although the reference says it will have similar results I would add it):
The default implementation of this JS serialization mechanism will
look for the Jackson library in the classpath and, if present, will
use it. If not, it will apply a built-in serialization mechanism that
covers the needs of most scenarios and produces similar results (but
is less flexible).
Finally, try to log users content (console.log(users)) to see what is doing the serialization.
Java mapping
Other easier way is If you want to iterate a list of java objects yous could map it to a Json in Java (using a library like Jackson or Gson) and then add it as parameter to the thymeleaf template.
ObjectMapper mapper = new ObjectMapper();
String users = mapper.writeValueAsString(users);
model.addAttribute("users", users);
The result of the parameter will be in a JSON format.

Run set names query, and json unicode on laravel

I'm new on Laravel
and I search for a way to run queries
I'm not talking about select etc...
I want to run this query:
SET NAMES 'utf8'
This is question number one,
Now question number two:
I have data writen in hebrew in my db
and when I do on Laravel this code:
$todolist = DB::select('select * from todo');
return $todolist;
I get this result:
[{"id":1,"name":"\u05d1\u05dc\u05d4 \u05d1\u05dc\u05d4 \u05d1\u05dc\u05d4","done":0},{"id":2,"name":"\u05d1\u05dc\u05d4 \u05d1\u05dc\u05d4 \u05d1\u05dc\u05d4","done":1}]
What is this? unicode? how can I turn it to hebrew again?
My mission is to send it back to client side and then show it on the web page
How can I translate this from unicode to hebrew with Java Script ?
You can use the statement method of the DB class, like so:
DB::statement("SET NAMES 'utf8'");
I'm not entirely aware of the situation but I would recommend this be within a migration.
Regarding the unicode characters, those should render in views correctly and should be usable within Javascript (see http://codepen.io/anon/pen/LZpOqY)

Sails.js - Have a 'contains' or query in url to fetch appropriate JSON data

My Sails.js application has a model called 'Ideas' and using the default blueprint REST api, I can access the contents of the collection when I go to: http://example.com/ideas/find
Furthermore, by default, I can also limit the data to get specific titles: http://example.com/ideas/find?title=How to Watch TV
Although what I want to do is display the JSON data of ALL titles that contain the keyword 'T' but when I replace the above with the likes of
a) ?title=TV
b) ?q=TV
c) ?query=TV
d) ?where(title : (contains:'TV')
none of them work
How can I get JSON output that contains all titles that contains a particular keyword?
Based on the documentation, the where example should work. It uses curly brackets instead of parenthesis though.
?where={"title":{"contains":"TV"}}
For multiple use ",".
Example :
ideas/find?where={"title":{"contains":"music"}},{"title":{"contains":"film"}}

How to handle indices in Neo4j server via javascript REST client?

I have data in a standalone Neo4j REST server, including an index of nodes. I want pure JavaScript client to connect to Neo4j and serve the formatted data to d3.js, a visualisation library built on Node.js.
JugglingDB is very popular, but the Neo4j implementation was done "wrong": https://github.com/1602/jugglingdb/issues/56
The next most popular option on github is: https://github.com/thingdom/node-neo4j
looking at the method definitions https://github.com/thingdom/node-neo4j/blob/develop/lib/GraphDatabase._coffee
I'm able to use "getNodeById: (id, _) ->"
> node1 = db.getNodeById(12, callback);
returns the output from the REST server, including node properties. Awesome.
I can't figure out how to use "getIndexedNodes: (index, property, value, _) ->"
> indexedNodes = db.getIndexedNodes:(index1, username, Homer, callback);
...
indexedNodes don't get defined. I've tried a few different combinations. No joy. How do I use this command?
Also, getIndexedNodes() requires a key-value pair. Is there any way to get all, or a subset of the items in the index without looping?
One of the authors/maintainers of node-neo4j here. =)
indexedNodes don't get defined. I've tried a few different combinations. No joy. How do I use this command?
Your example seems to have some syntax errors. Are index1, username and Homer variables defined elsewhere? Assuming not, i.e. assuming those are the actual index name, property name and value, they need to be quoted as string literals, e.g. 'index1', 'username' and 'Homer'. But you also have a colon right before the opening parenthesis that shouldn't be there. (That's what's causing the Node.js REPL to not understand your command.)
Then, note that indexedNodes should be undefined -- getIndexedNodes(), like most Node.js APIs, is asynchronous, so its return value is undefined. Hence the callback parameter.
You can see an example of how getIndexedNodes() is used in the sample node-neo4j-template app the README references:
https://github.com/aseemk/node-neo4j-template/blob/2012-03-01/models/user.js#L149-L160
Also, getIndexedNodes() requires a key-value pair. Is there any way to get all, or a subset of the items in the index without looping?
getIndexedNodes() does return all matching nodes, so there's no looping required. Getting a subset isn't supported by Neo4j's REST API directly, but you can achieve the result with Cypher.
E.g. to return the 6th-15th user (assuming they have a type property set to user) sorted alphabetically by username:
db.query([
'START node=node:index1(type="user")',
'RETURN node ORDER BY node.username',
'SKIP 5 LIMIT 10'
].join('\n'), callback);
Cypher is still rapidly evolving, though, so be sure to reference the documentation that matches the Neo4j version you're using.
As mentioned above, in general, take a look at the sample node-neo4j-template app. It covers a breadth of features that the library exposes and that a typical app would need.
Hope this helps. =)
Neo4j 2 lets you do indices VIA REST. Docs here
REST Indicies

Lucene-like searching through JSON objects in JavaScript

I have a pretty big array of JSON objects (its a music library with properties like artist, album etc, feeding a jqgrid with loadonce=true) and I want to implement lucene-like (google-like) query through whole set - but locally, i.e. in the browser, without communication with web server. Are there any javascript frameworks that will help me?
Go through your records, to create a one time index by combining all search
able fields in a single string field called index.
Store these indexed records in an Array.
Partition the Array on index .. like all a's in one array and so on.
Use the javascript function indexOf() against the index to match the query entered by the user and find records from the partitioned Array.
That was the easy part but, it will support all simple queries in a very efficient manner because the index does not have to be re-created for every query and indexOf operation is very efficient. I have used it for searching up to 2000 records. I used a pre-sorted Array. Actually, that's how Gmail and yahoo mail work. They store your contacts on browser in a pre-sorted array with an index that allows you to see the contact names as you type.
This also gives you a base to build on. Now you can write an advanced query parsing logic on top of it. For example, to support a few simple conditional keywords like - AND OR NOT, will take about 20-30 lines of custom JavaScript code. Or you can find a JS library that will do the parsing for you the way Lucene does.
For a reference implementation of above logic, take a look at how ZmContactList.js sorts and searches the contacts for autocomplete.
You might want to check FullProof, it does exactly that:
https://github.com/reyesr/fullproof
Have you tried CouchDB?
Edit:
How about something along these lines (also see http://jsfiddle.net/7tV3A/1/):
var filtered_collection = [];
var query = 'foo';
$.each(collection, function(i,e){
$.each(e, function(ii, el){
if (el == query) {
filtered_collection.push(e);
}
});
});
The (el == query) part of course could/should be modified to allow more flexible search patterns than exact match.

Categories