how to implement $size in spring Data Aggregation in java - java

how to implement below code in java using spring Data mongodb
db.profil.aggregate([
{ "$match": { "typ": "Organisation" } },
{ "$group": {
"_id": null,
"count": {
"$sum": { "$size": "$foos" }
}
} }
])

MongoDB has an Aggregation framework for Java to support all aggregation APIs.
Try following:
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.*;
Bson match = match(eq("typ", "Organisation")));
Bson projection = new Document("$size", "$foos" );
Bson group = group("$_id", Accumulators.sum("count",projection));
MongoCursor<Document> cursor = collection.aggregate(asList(match, group)).iterator();

Related

Using Jaca JsonPath to exclude items from JSON response

I am using the JsonSmartJsonProvider and my JSON looks like this
{
"info": {
"clientCount": 1,
"compactorVersion": 2,
"processMonitor": {
"processList": [
{
"name": "java.exe",
"commandLine": "",
"pid": 6224
}
]
}
}
}
I'm trying to exclude "processList", but keep everything else. I've tried variations on $.info[?(# noneof ['processMonitor'])], but I always end up with "info" being empty in the response. Is it possible to use JsonPath to do this? The code that is used to do this looks like this:
DocumentContext document = JsonPath.using(CONFIGURATION).parse(json);
Map<String, Object> result = new HashMap<>();
paths.forEach((key, value) -> result.put(key, document.read(value)));
return result;
As mentioned, you are actually looking for a JSON transformation. JOLT is a common library to do just that. A solution can look like this:
import java.util.List;
import com.bazaarvoice.jolt.Chainr;
import com.bazaarvoice.jolt.JsonUtils;
public class MyJsonTransformer {
public static void main(String[] args) throws Exception {
List<Object> specs = JsonUtils.classpathToList("/spec.json");
Chainr chainr = Chainr.fromSpec(specs);
Object inputJSON = JsonUtils.classpathToObject("/input.json");
Object transformedOutput = chainr.transform(inputJSON);
System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
}
}
And a jolt remover spec file like this:
[
{
"operation": "remove",
"spec": {
"info": {
"processMonitor": {
"processList": ""
}
}
}
}
]
You can try JOLT online with your input and the spec above here. Pretty neat.
The JSON and spec can be defined inline as well. I have not tested this end to end.

Recording sales amount in datadog metrics

I'm trying to record my website sales $ amount in datadog. However I'm getting way more than the actual value.
I'm using java-dogstatsd client and spring. My application is running on 3 hosts. I recorded all metrics (using sendWebOrder method) but no luck.
#EnableConfigurationProperties({DataDogProperties.class})
#Component
public class DDMetrics {
#Autowired
DataDogProperties dataDogProperties;
#Autowired
private NonBlockingStatsDClient statsd;
private Map<TopicPartition,Long> lags = new HashMap<>();
#Bean
private NonBlockingStatsDClient initClient() {
NonBlockingStatsDClient metricsClient = new NonBlockingStatsDClient(
dataDogProperties.getServiceName(),
dataDogProperties.getHostname(),
dataDogProperties.getPort();
return metricsClient;
}
public void sendWebOrder(WebOrder webOrder) {
List<String> tags = new ArrayList<>();
tags.add("transactionType:" + webOrder.getTransactionType());
tags.add("dataSourceType:" + webOrder.getDataSourceType()));
statsd.count("amount_count", webOrder.getAmount(), String.join(",", tags));
statsd.recordDistributionValue("amount_dist", webOrder.getAmount(), String.join(",", tags));
statsd.recordHistogramValue("amount_hist", webOrder.getAmount(), String.join(",", tags));
statsd.recordGaugeValue("amount_gauge", webOrder.getAmount(), String.join(",", tags));
statsd.incrementCounter("weborder", String.join(",", tags));
}
I'm trying to generate a datadog toplist by transactiontype. I'm not getting the correct amount in any of the metrics (tried mainly count, gauge and histogram.sum). Here is my datadog config:
{
"viz": "toplist",
"requests": [
{
"q": "top(sum:projecta.webtransactions.amount_histogram.sum{$TransactionType} by {transactiontype}, 10, 'sum', 'desc')",
"type": "area",
"style": {
"palette": "dog_classic",
"type": "solid",
"width": "normal"
},
"aggregator": "sum",
"conditional_formats": []
}
],
"autoscale": true
}
What am I missing? Is this the correct way to record money value? Do I've to do any rollup in config?
Any help is appreciated.

Is it possible to get variable from Java class to a html file

I'd like to use the swaggerjson String, to define as a var in a html file.
private static BeanConfig beanConfig = new BeanConfig();
public EtelApplication() {
printPath();
beanConfig.setTitle("jim-rest");
beanConfig.setResourcePackage("com.mast.api");
beanConfig.setScan(true);
beanConfig.scanAndRead();
printSwaggerJson();
createSwaggerJsonFile();
}
private void printSwaggerJson() {
String swaggerjson = Json.pretty(beanConfig.getSwagger());
System.out.println(swaggerjson);
}
My html file has this script, where I would like to use the string
window.onload = function () {
const ui = SwaggerUIBundle({name */
url: "swagger.json", name: "jim-rest",
dom_id: '#swagger-ui',
validatorUrl: null,
deepLinking: true,
spec: swaggerjson, //this is where I would like to use the var.
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
is it possible to use swaggerjson directly like this?
I aplogise for the very simple question, I wasn't able to find a detailed answer when searching

Control how an elasticsearch java QueryBuilder is converted into a String

The following code emits an elasticsearch query that is too verbose for my liking -
import org.elasticsearch.index.query.QueryBuilder;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
public class MyQueryPrinter {
public static void main(String[] args) {
QueryBuilder myQuery = termQuery("brand", "gucci");
System.out.println(myQuery.toString());
/* prints -
{
"term" : {
"brand" : {
"value" : "gucci",
"boost" : 1.0
}
}
}
*/
}
}
I'd like to print the shortest possible query json-
{
"term" : {
"brand" : "gucci"
}
}
The code also automatically "pretty-prints" (i.e. indents) the json.
How can I control how QueryBuilder is converted into a String?
Thanks!!
p.s. - I'm using Elasticsearch 5.5.3 via maven -
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.3</version>
</dependency>

How can I retrieve a child property using #JsonProperty?

I have the following metadata for the artist Joseph Turner:
{
"activePlaceCount":0,
"birth":{
"place":{
"name":"London, United Kingdom",
"placeName":"London",
"placeType":"inhabited_place"
},
"time":{
"startYear":1775
}
},
"birthYear":1775,
"date":"1775\u20131851",
"death":{
"place":{
"name":"Chelsea, United Kingdom",
"placeName":"Chelsea",
"placeType":"neighbourhood"
},
"time":{
"startYear":1851
}
},
"fc":"Joseph Mallord William Turner",
"gender":"Male",
"id":558,
"mda":"Turner, Joseph Mallord William",
"movements":[
{
"era":{
"id":290,
"name":"18th century"
},
"id":345,
"name":"Picturesque"
},
{
"era":{
"id":350,
"name":"19th century"
},
"id":364,
"name":"Romanticism"
},
{
"era":{
"id":290,
"name":"18th century"
},
"id":349,
"name":"Sublime"
}
],
"startLetter":"T",
"totalWorks":41861,
"url":"http://www.tate.org.uk/art/artists/joseph-mallord-william-turner-558"
}
If I wanted to map fc to firstName in my Java program, I could simply do the following:
#JsonProperty("fc")
private String fullName;
That, or private String fc.
What would I do if wanted to retrieve "death"."time"."startYear"?
Based on this SO answer, it is currently not possible to create an annotation of this sort, but it is a ticket for the future (updates of Java).

Categories

Resources