#Query ignored in ElasticSearch Spring java framework - spring

I have this interface defined in Spring for querying Elascticsearch. I added #Query annotation to get some filtering done.
public interface ObjectElasticSearch extends ElasticsearchRepository<ElasticObject, String> {
#Query("{\"query\" : {\"filtered\" : {\"filter\" : { \"and\" : [ { \"term\" : { \"firstName\" : \":firstName\" }}, { \"term\" : { \"lastName\" : \"Baggins\" }} ] }}}}")
List<ElasticObject> findByDocFirstNameAndDocLastName(#Param("firstName") String firstName,
#Param("lastName") String lastName);
};
The #Query annotation gets ignored completely. As you can see I tried hardcoding last name, and it has no effect on the outcome of the query. If I delete a curly brace in the query string, I don't get any errors. Query still works, the filtering is ignored, and it returns all matches.
Can someone please help me figure out what am I doing wrong here.

Query should return a bool that in a must section can cover all your searches.
Here is my example that works for me, I have a records with startTimestamp and endTimestamp, and my method will find all of them that overlap specified timeframe + match fields by query
#Query("{\"bool\": {\"must\":["
+ " {\"range\": {\"endTimestamp\": {\"gte\": ?0}}},"
+ " {\"range\": {\"startTimestamp\": {\"lte\": ?1}}}"
+ " ], \"should\": ["
+ " {\"match\": {\"_all\": {\"query\": \"?2\", \"zero_terms_query\": \"all\"}}}"
+ " ],"
+ " \"minimum_should_match\" : 1"
+ " }"
+ "}")

Related

Spring Data MongoDB SpEL Expression injection vulnerability

According to the vulnerability report (https://tanzu.vmware.com/security/cve-2022-22980), it's clearly affect for the Spel expressions like this.
#Query("{ 'userName' : ?#{?0}}")
But I just wanted to confirm, is that affect to followings too.
#Query(value = "{ '_id' : {$exists : true} }", fields = "{'_id' : 1,'customerId' : 1}")
or
#Query("{ 'name': ?0, 'customerId': ?1 }")

strapi.JS GRAPHQL ERROR "Expected value of type \"StringFilterInput\", found \”anna\”.”,

I'm try GraphQL with strapi.JS and get error in http://localhost:1337/graphql
Very similar work well previously in other website. I'm try before changing other user nothing work.
Here full error:
{
"error": {
"errors": [
{
"message": "Expected value of type \"StringFilterInput\", found \"ann.bystry\".",
"locations": [
{
"line": 2,
"column": 58
}
],
"extensions": {
"code": "GRAPHQL_VALIDATION_FAILED",
"exception": {
"stacktrace": [
"GraphQLError: Expected value of type \"StringFilterInput\", found \"ann.bystry\".",
" at isValidValueNode (/Users/ann.bystry/annblogstry/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js:118:25)",
" at Object.StringValue (/Users/ann.bystry/annblogstry/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js:93:14)",
" at Object.enter (/Users/ann.bystry/annblogstry/node_modules/graphql/language/visitor.js:323:29)",
" at Object.enter (/Users/ann.bystry/annblogstry/node_modules/graphql/utilities/TypeInfo.js:370:25)",
" at visit (/Users/ann.bystry/annblogstry/node_modules/graphql/language/visitor.js:243:26)",
" at validate (/Users/ann.bystry/annblogstry/node_modules/graphql/validation/validate.js:69:24)",
" at validate (/Users/ann.bystry/annblogstry/node_modules/apollo-server-koa/node_modules/apollo-server-core/dist/requestPipeline.js:185:39)",
" at processGraphQLRequest (/Users/ann.bystry/annblogstry/node_modules/apollo-server-koa/node_modules/apollo-server-core/dist/requestPipeline.js:90:34)",
" at runMicrotasks (<anonymous>)",
" at processTicksAndRejections (internal/process/task_queues.js:95:5)",
" at async processHTTPRequest (/Users/ann.bystry/annblogstry/node_modules/apollo-server-koa/node_modules/apollo-server-core/dist/runHttpQuery.js:183:30)",
" at async /Users/ann.bystry/annblogstry/node_modules/apollo-server-koa/dist/ApolloServer.js:82:59",
" at async bodyParser (/Users/ann.bystry/annblogstry/node_modules/koa-bodyparser/index.js:95:5)",
" at async cors (/Users/ann.bystry/annblogstry/node_modules/#koa/cors/index.js:98:16)",
" at async returnBodyMiddleware (/Users/ann.bystry/annblogstry/node_modules/#strapi/strapi/lib/services/server/compose-endpoint.js:52:18)",
" at async policiesMiddleware (/Users/ann.bystry/annblogstry/node_modules/#strapi/strapi/lib/services/server/policy.js:28:5)"
]
}
}
}
]
}
}
welcome to Stackoverflow, glad to see you are starting out with Strapi!
If I understand right, you are referring to V4, if you used V3 before, then as #xadm pointed out you likely are providing incorrect input for your GraphQL query filters.
You can always find the definition (the parameters it accepts and the format of them) for StringFilterInput and any other types by clicking on the green "DOCS" label on the right hand side of your GraphQL Playground (Screenshot below):
With this in mind you may want to try querying with the below query (replacing posts with the Collection Type you are searching for)
*also note the " eq: in username filter
query {
posts(filters: { author: { username: { eq: "ann.bystry" } } }) {
data {
id
attributes {
title
# query other fields here
}
}
}
}
Friendly suggestion for future - when you ask a question it is always useful to paste in any relevant code samples and versions of the frameworks/packages you are using :)
Best of luck!

Spring MongoDB : querying documents with two equal fields

I want to query that returns document that two fields of it are equal
I found mongodb raw query from this question :
db.coll.find({ $where : "this.field1 == this.field2" } );
How can I perform it with spring criteria:
criteria = criteria.andOperator(
Criteria.where("successfulSent").is("true"),
Criteria.where("this.fieldOne == this.fieldTwo"));
but its not working beacuse generated query become :
{ ... "$and" : [ { "successfulSent" : "true"} , { "this.fieldOne == this.fieldOne " : { }}]}
You can try on this way:
Criteria.where("$where").is("this.field1 == this.field2")
Query toString() will be:
Query: { "$where" : "this.cts == this.uts"}, Fields: null, Sort: null

Spring data mongodb: Optional #Query parameter no longer works

After upgrading to spring data mongodb 1.10.1, I am getting errors when running queries like:
#Query("{$and :["
+ "{ $or : [ { $where: '?0 == null' } , { 'field1' : ?0 } ] },"
+ "{ $or : [ { $where: '?1 == null' } , { 'field2' : ?1 } ] },"
+ "]}")
public Page<Entity> findAll(String param1, String param2)
Checking the error I see the parameter inside the where clause is not quoted and as I result I get:
org.springframework.data.mongodb.UncategorizedMongoDbException: Query
failed with error code 139 and error message 'ReferenceError:
test_param_value is not defined :
I have seen a few answers here recommending this way of handling optional parameters ((spring-data-mongo - optional query parameters?)) but it no longer works and I cannot seem to find anything in the release change log.
In case anyone else is interested, I managed to find a workaround after checking a similar ticket int the Spring Data project.
It seems the way I was checking for null parameters in the query is not a good practice. This is from a Spring developer comment: "placeholders are not designed to compose keys/values but bind parameters. Beyond that, placeholder use in quoted strings is always problematic in terms of escaping. Using SpEL should suit your needs"
So I ended up using SpEL to do the checks on parameters and it works fine. This is how it looks:
#Query("{$and :["
+ "?#{ [0] == null ? { $where : 'true'} : { 'field1' : [0] } },"
+ "?#{ [1] == null ? { $where : 'true'} : { 'field2' : [1] } },"
+ "]}")
public Page<Entity> findAll(String param1, String param2, Pageable pageable);

Couchbase CRUD operations with query language

Im using couchbase 4.0 beta version. And Im successfully able to save the objects into the bucket using rest service. Now I need to access the bucket and do GET, UPDATE and DELETE operations using queries.
This is the my sample object in bucket.
{
"id": "friend$43403778",
"domain": "FRIEND",
"profileId": 43403778,
"screenName": "49ers",
"name": "San Francisco 49ers",
"profileUrl": "http://twitter.com/49ers",
"description": "Official Twitter account of the five-time Super Bowl Champion San Francisco #49ers.",
"friendsCount": 121,
"followersCount": 964650,
"timeZone": "Pacific Time (US & Canada)",
"utcOffset": -25200,
"location": "Santa Clara, CA",
"profileCreated": 1243629277000
}
Now I want to get this object using id. But id value contains special character so my query doesn't works for it. How can I access it???
This is my code snippet which I tried to get this.It doesn't gives me the 300 error code syntax error.
String strQuery = "SELECT * FROM twitter WHERE id=" + id;
Bucket bucket = singletonBucket.getBucket();
QueryResult queryResult = bucket.query(Query.simple(strQuery));
List<QueryRow> result = Collections.emptyList();
if (!queryResult.finalSuccess()) {
log.error("Error occur while retrieving TwitterProfile document for id: {}",id);
String errorStr = "";
for (JsonObject error : queryResult.errors()) {
errorStr = error.toString() + ". ";
log.error("{}", error);
}
throw new DataAccessException(errorStr);
} else {
result = queryResult.allRows();
for(QueryRow row: result){
Object doc = row.value().get(AppConstants.BUCKET_NAME);
TwitterProfile twitterProfile = objectMapper.readValue(doc.toString(), TwitterProfile.class);
twitterProfileList.add(twitterProfile);
}
log.info("Successfully found {} TwitterProfile record for id {}",twitterProfileList.size(), id);
return twitterProfileList.size()>0 ?twitterProfileList.get(0):"";
}
If I tried to get the record using profileId It also doesnt work.
How can I write the simple queries for this bucket.
These are the queries which I tried. Also my bucket name is twitter
String strQuery = "SELECT * FROM twitter WHERE domain=" + AppConstants.DOMAIN_FRIEND;
String strQuery = "DELETE FROM twitter WHERE domain=" + AppConstants.DOMAIN_FRIEND;
Thanks in advance.
When building your query you have to use quotes to indicate your id is a string. Try adding quotes around your id when building your query:
String strQuery = "SELECT * FROM twitter WHERE id='" + id + "'";

Resources