Elasticsearch mapping not working with numeric - java

I have written elasticsearch mapping its only only with alphabets. how to do the same for numeric values.
PUT /documents_test8
{
"settings" : {
"analysis" : {
"analyzer" : {
"filename_search" : {
"tokenizer" : "filename",
"filter" : ["lowercase"]
},
"filename_index" : {
"tokenizer" : "filename",
"filter" : ["lowercase","edge_ngram"]
}
},
"tokenizer" : {
"filename" : {
"pattern" : "[^\\p{L}\\d]+",
"type" : "pattern"
}
},
"filter" : {
"edge_ngram" : {
"side" : "front",
"max_gram" : 20,
"min_gram" : 1,
"type" : "edgeNGram"
}
}
}
},
"mappings" : {
"doc" : {
"properties" : {
"filename" : {
"type" : "text",
"search_analyzer" : "filename_search",
"index_analyzer" : "filename_index"
}
}
}
}
}

For numeric, you can define the mapping like this using type as "long"
"type": "long"
And for floating point number, use using type as "float"
"type": "float"

Related

QueryString to search String with colon

i am trying to achieve below condition
orgId = "z2store" and type = "web" and dateTime = "12:17:08"
below query i have written
GET /sample/_search
{
"bool" : {
"must" : [
{
"term" : {
"orgId" : {
"value" : "z2store",
"boost" : 1.0
}
}
},
{
"term" : {
"type" : {
"value" : "web",
"boost" : 1.0
}
}
},
{
"query_string" : {
"query" : "12:17:08",
"default_field" : "dateTime",
"fields" : [ ],
"type" : "best_fields",
"default_operator" : "or",
"max_determinized_states" : 10000,
"enable_position_increments" : true,
"fuzziness" : "AUTO",
"fuzzy_prefix_length" : 0,
"fuzzy_max_expansions" : 50,
"phrase_slop" : 0,
"escape" : false,
"auto_generate_synonyms_phrase_query" : true,
"fuzzy_transpositions" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
below is my java code
BoolQueryBuilder boolQuery = new BoolQueryBuilder().must(QueryBuilders.termQuery("orgId", orgId))
.must(QueryBuilders.termQuery("type", "web"));
QueryStringQueryBuilder builder = new QueryStringQueryBuilder("12:17:08");
builder.defaultField("dateTime").queryString();
boolQuery.must(builder);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(builder)
.from((batchNumber - 1) * batchSize).size(batchSize)
.sort("#timestamp", SortOrder.DESC);
Above query is not working. Any help will be appreciated. I am using elasticSearch 7.4.
You can create your dateTime field with type as date and giving format as hour_minute_second(which takes format as HH:mm:ss) . You can read more about different date formats here https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-date-format.html.
Below is the mapping of dateTime field:
{
"mappings": {
"properties": {
"dateTime": {
"type" : "date",
"format" : "hour_minute_second"
}
}
}
}
Now when you search data with below search query :
{
"query" : {
"bool" : {
"must" : [
{
"term" : {
"orgId" : {
"value" : "z2store",
"boost" : 1.0
}
}
},
{
"term" : {
"type" : {
"value" : "web",
"boost" : 1.0
}
}
},
{
"term" :{
"dateTime":"12:17:08"
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
}
You will get your required result :
"hits": [
{
"_index": "datetimeindexf",
"_type": "_doc",
"_id": "1",
"_score": 1.5753641,
"_source": {
"dateTime": "12:17:08",
"orgId": "z2store",
"type": "web"
}
}
]

mongo $near command on Nested Array

{
"merchantId" : "M168976258",
"catalogTypeId" : "catalogTypeProduct",
"items" : [
{
"name" : "Product 1",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
},
{
"name" : "Product 2",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
},
{
"name" : "Product 3",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
}
}
I able to Perfrom mongo near command on document which is having single location
using below command
db.abc.find({
location :{
$near : {
$geometry : {
index : "Point" ,
coordinates : [19.1, 72.89]
},
$maxDistance : 10000
}
}
})
but i'm not able to perform on document which having nested array can anybody help me out to find out problem
By running this query i get following error
db.catalogForAdminAndMerchant.find({
"items.location" :{
$near : {
$geometry : {
index : "Point" ,
coordinates : [19.1, 72.89]
},
$maxDistance : 10000
}
}
})
o/p is
planner returned error: unable to find index for $geoNear query
but have created the index
by running db.catalogForAdminAndMerchant.getIndexes() i get
/* 1 */
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "catalog-db.catalogForAdminAndMerchant"
},
/* 2 */
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "CatalogForAdminAndMerchant_TextIndex",
"ns" : "catalog-db.catalogForAdminAndMerchant",
"weights" : {
"items.name" : 3
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
},
/* 3 */
{
"v" : 2,
"key" : {
"address.items[i].location" : "2dsphere"
},
"name" : "address.items[i].location_2dsphere",
"ns" : "catalog-db.catalogForAdminAndMerchant",
"2dsphereIndexVersion" : 3
}

Accessing the "_embedded" data in spring data REST interface

The project is a visual analysis of business data, MongoDB through Spring Data, REST interface, then d3.js.
On the database level, my data looks like this:
/* 1 */
{
"_id" : ObjectId("58ac466160fb39e5e8dc8b70"),
"dots" : {
"x" : 4,
"y" : 3
}
}
/* 2 */
{
"_id" : ObjectId("58ac468060fb39e5e8dc8b7e"),
"squares" : {
"x" : 12,
"y" : 2
}
}
The REST interface (spring) delivers this:
{
"_embedded" : {
"JSON" : [ {
"squares" : null,
"dots" : {
"dot" : {
"x" : 4,
"y" : 3
}
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/JSON/58ac466160fb39e5e8dc8b70"
},
"jSON" : {
"href" : "http://localhost:8080/JSON/58ac466160fb39e5e8dc8b70"
}
}
}, {
"squares" : {
"square" : {
"x" : 12,
"y" : 2
}
},
"dots" : null,
"_links" : {
"self" : {
"href" : "http://localhost:8080/JSON/58ac468060fb39e5e8dc8b7e"
},
"jSON" : {
"href" : "http://localhost:8080/JSON/58ac468060fb39e5e8dc8b7e"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/JSON"
},
"profile" : {
"href" : "http://localhost:8080/profile/JSON"
}
},
"page" : {
"size" : 20,
"totalElements" : 2,
"totalPages" : 1,
"number" : 0
}
}
Now I'm having trouble accessing this for processing in d3.js for visualization, whatever way I try to access the data, I only get "undefined" with no values back on the console.
Should I reformat to get rid of the "_embedded" part, or to "flatten" the data generally, or do I need a specific way to access it?
As of now, I'm just using "d3.json("/JSON")" to access the interface, but can't extract any data.

ElasticSearch Nested Object Mapping

I have created following mapping for in ElasticSearch and same is created. But when I add documents to this type, my nested field type
changes to normal. So when I execute query on nested object fields,it
shows unexpected results while on rest of the fields results are as
expected. I am not sure what I am doing wrong. There must be something
I am missing while creating nested object mapping.
request_body = {
"settings": {
"index": {
"analysis": {
"analyzer": {
"standard": {
"tokenizer": "standard",
"filter": ["lowercase", "stop"]
}
}
}
}
},
"mappings" : {
"userdetails" : {
"properties" : {
"accountType" : {
"type" : "long"
},
"addressLineOne" : {
"type" : "string"
},
"addressLineTwo" : {
"type" : "string"
},
"alternateEmailId" : {
"type" : "string"
},
"archiveId" : {
"type" : "string"
},
"blockedEmployerId" : {
"type" : "long"
},
"cityId" : {
"type" : "long"
},
"country" : {
"type" : "string"
},
"coverPicUrl" : {
"type" : "string"
},
"currentEmployer" : {
"type" : "string"
},
"currentPackageCurrencyId" : {
"type" : "long"
},
"currentPackageUnit" : {
"type" : "string"
},
"currentSalaryPackage" : {
"type" : "double"
},
"currentlocation" : {
"type" : "string"
},
"designation" : {
"type" : "string"
},
"emailId" : {
"type" : "string"
},
"employmentDetail" : {
"type":"nested",
"properties" : {
"companyName" : {
"type" : "string"
},
"designation" : {
"type" : "string"
},
"durationEndMonth" : {
"type" : "long"
},
"durationEndYear" : {
"type" : "long"
},
"durationStartMonth" : {
"type" : "long"
},
"durationStartYear" : {
"type" : "long"
},
"employmentStatus" : {
"type" : "string"
},
"id" : {
"type" : "long"
},
"isCurrent" : {
"type" : "long"
},
"jobProfile" : {
"type" : "string"
},
"location" : {
"type" : "string"
},
"timeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"userId" : {
"type" : "long"
}
}
},
"examscores" : {
"type":"nested",
"properties" : {
"attemptedCount" : {
"type" : "long"
},
"candidateId" : {
"type" : "long"
},
"examDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"examId" : {
"type" : "long"
},
"examScoreDetailId" : {
"type" : "long"
},
"examTotalScore" : {
"type" : "double"
},
"examType" : {
"type" : "long"
},
"katExamEventId" : {
"type" : "long"
},
"rightAttempted" : {
"type" : "long"
},
"rptVisStatus" : {
"type" : "long"
},
"scorePercent" : {
"type" : "double"
},
"timeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"token" : {
"type" : "string"
},
"totalQuestion" : {
"type" : "long"
},
"totalScore" : {
"type" : "double"
}
}
},
"experienceInMonths" : {
"type" : "long"
},
"experienceInYears" : {
"type" : "long"
},
"firstName" : {
"type" : "string"
},
"gender" : {
"type" : "string"
},
"hQPS" : {
"type" : "long"
},
"higestQualInstitute" : {
"type" : "string"
},
"higestQualInstituteLoc" : {
"type" : "string"
},
"higestQualPassingYear" : {
"type" : "long"
},
"higestQualPercentCgpa" : {
"type" : "double"
},
"higestQualification" : {
"type" : "string"
},
"highestQualSpecialization" : {
"type" : "string"
},
"highestQualificationStream" : {
"type" : "string"
},
"industryDomain" : {
"type" : "string"
},
"keySkills" : {
"type" : "string"
},
"lastLoginDate" : {
"type" : "string"
},
"lastName" : {
"type" : "string"
},
"lastUpdateDate" : {
"type" : "string"
},
"locationName" : {
"type" : "string"
},
"maritalStatus" : {
"type" : "string"
},
"mobileNumber" : {
"type" : "long"
},
"password" : {
"type" : "string"
},
"paswdChangedDate" : {
"type" : "string"
},
"phoneNumber" : {
"type" : "long"
},
"preferredLocations" : {
"type" : "string"
},
"profileImageUrl" : {
"type" : "string"
},
"profileSummary" : {
"type" : "string"
},
"projectdetail" : {
"type":"nested",
"properties" : {
"clientName" : {
"type" : "string"
},
"designation" : {
"type" : "string"
},
"durationEndMonth" : {
"type" : "long"
},
"durationEndYear" : {
"type" : "long"
},
"durationStartMonth" : {
"type" : "long"
},
"durationStartYear" : {
"type" : "long"
},
"employmentNature" : {
"type" : "long"
},
"id" : {
"type" : "long"
},
"location" : {
"type" : "string"
},
"rolesResponsibilities" : {
"type" : "string"
},
"skillsUsed" : {
"type" : "string"
},
"teamSize" : {
"type" : "long"
},
"timeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"title" : {
"type" : "string"
},
"userId" : {
"type" : "long"
}
}
},
"qualification" : {
"type":"nested",
"properties" : {
"id" : {
"type" : "long"
},
"institute" : {
"type" : "string"
},
"isPrimary" : {
"type" : "long"
},
"passingYear" : {
"type" : "long"
},
"percentageCgpa" : {
"type" : "double"
},
"qualification" : {
"type" : "string"
},
"specialization" : {
"type" : "string"
},
"timeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"userId" : {
"type" : "long"
}
}
},
"registrationDate" : {
"type" : "string"
},
"resumeContentType" : {
"type" : "string"
},
"resumeTitle" : {
"type" : "string"
},
"s3DocKey" : {
"type" : "string"
},
"s3HtmlKey" : {
"type" : "string"
},
"sectionalscores" : {
"type":"nested",
"properties" : {
"attemptedCount" : {
"type" : "long"
},
"candidateId" : {
"type" : "long"
},
"examScoreId" : {
"type" : "long"
},
"examTime" : {
"type" : "long"
},
"examTitleId" : {
"type" : "long"
},
"katExamId" : {
"type" : "long"
},
"katScoreId" : {
"type" : "long"
},
"rightAttempted" : {
"type" : "long"
},
"score" : {
"type" : "double"
},
"scorePercent" : {
"type" : "double"
},
"timeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"totalQuestion" : {
"type" : "long"
},
"totalScore" : {
"type" : "double"
}
}
},
"stateId" : {
"type" : "long"
},
"status" : {
"type" : "long"
},
"timeDate" : {
"type" : "string"
},
"userId" : {
"type" : "long"
},
"uuid" : {
"type" : "string"
},
"videoIntroType" : {
"type" : "long"
},
"videoIntroUrl" : {
"type" : "string"
},
"videoProfileTimeDate" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"videoProfileUrl" : {
"type" : "string"
},
"videoProfileVisibility" : {
"type" : "long"
},
"workStatusForOtherCountries" : {
"type" : "long"
},
"workStatusForUS" : {
"type" : "long"
},
"xIIPS" : {
"type" : "long"
},
"xIIPassingYear" : {
"type" : "long"
},
"xIIPercentageCgpa" : {
"type" : "double"
},
"xPS" : {
"type" : "long"
},
"xPassingYear" : {
"type" : "long"
},
"xPercentageCgpa" : {
"type" : "double"
}
}
}
}
}
print("creating 'example_index' index...")
res = es1.indices.create(index = 'no-one', body = request_body)
After creating index using above code, I added the data into this index using following code.
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import MySQLdb
import json
db = MySQLdb.connect(host='localhost',
user='xxxx',
passwd='xxxx',
db='xxxxx'
)
cursor_mysql = db.cursor()
cursor_mysql.execute("select * from USER ")
userTable = cursor_mysql.fetchall()
cursor_mysql.execute("select * from qualificationmapping")
secondaryQualification = cursor_mysql.fetchall()
cursor_mysql.execute("select * from examscoredetail")
examscore = cursor_mysql.fetchall()
cursor_mysql.execute("select * from katsectionalscore")
sectionalScore = cursor_mysql.fetchall()
cursor_mysql.execute("select * from projectexperiencedetails")
proejctDetails = cursor_mysql.fetchall()
cursor_mysql.execute("select * from useremploymentdetails")
employmentDetails = cursor_mysql.fetchall()
data = []
listSecondaryQualification=[]
listExamScores=[]
listSectionalScores=[]
listProjectDetails=[]
listEmploymentDetails=[]
# jsonSecondaryQualification = ''
# jsonExamScores = ''
# jsonSectionalScores = ''
# jsonProjectDetails = ''
# jsonEmploymentDetails = ''
# proejctdetail = {}
# qualification = {}
sectionalscores = {}
indexdata={}
# examscores = {}
# employmentDetail = {}
es1 = Elasticsearch()
# es1.create(index="xxxxx", doc_type='xxxx', body=indexdata)
count = 0
for userid in userTable:
count+=1
indexdata = {
"_index": "xxxxx",
"_type": "xxxxx",
"_id": userid[0]
}
for item in userTable:
if userid[0]== item[0]:
userdata = {
'userId': item[0],
'accountType': item[1],
'addressLineOne': item[2],
'addressLineTwo': item[3],
'alternateEmailId': item[4],
'archiveId':item[5],
'blockedEmployerId': item[6],
'cityId': item[7],
'classXIISchool': item[8],
'classXSchool': item[9],
'country': item[10],
'coverPicUrl': item[11],
'currentEmployer': item[12],
'currentPackageCurrencyId': item[13],
'currentPackageUnit': item[14],
'currentSalaryPackage': item[15],
'currentlocation': item[16],
'designation': item[17],
'emailId': item[19],
'experienceInMonths': item[20],
'experienceInYears': item[21],
'firstName': item[22],
'gender': item[23],
'hQPS': item[24],
'higestQualInstitute': item[25],
'higestQualInstituteLoc': item[26],
'higestQualPassingYear': item[27],
'higestQualPercentCgpa': item[28],
'higestQualification': item[29],
'highestQualSpecialization': item[30],
'highestQualificationStream': item[31],
'industryDomain': item[32],
'keySkills': item[33],
'lastLoginDate': str(item[34]),
'lastName': item[35],
'lastUpdateDate': str(item[36]),
'locationName': item[37],
'maritalStatus': item[38],
'middleName': item[39],
'mobileNumber': item[40],
'password': item[41],
'paswdChangedDate': item[42],
'phoneNumber': item[43],
'preferredLocations': item[44],
'previousEmployer': item[45],
'profileImageUrl': item[46],
'profileSummary': item[47],
'registrationDate': str(item[48]),
'resumeContentType': item[49],
'resumeTitle': item[50],
's3DocKey': item[51],
's3HtmlKey': item[52],
'stateId': item[53],
'status': item[54],
'timeDate': str(item[55]),
'uuid': item[56],
'videoIntroType': item[57],
'videoIntroUrl': item[58],
'videoProfileTimeDate': item[59],
'videoProfileUrl': item[60],
'videoProfileVisibility': item[61],
'workStatusForOtherCountries': item[62],
'workStatusForUS': item[63],
'xIIPS': item[64],
'xIIPassingYear': item[65],
'xIIPercentageCgpa': item[66],
'xPS': item[67],
'xPassingYear': item[68],
'xPercentageCgpa': item[69]
}
for quid in secondaryQualification:
if userid[0]== quid[8]:
indQualification = {
'id': quid[0],
'institute': quid[1],
'isPrimary': quid[2],
'passingYear': quid[3],
'percentageCgpa': quid[4],
'qualification': quid[5],
'specialization': quid[6],
'timeDate': str(quid[7]),
'userId': quid[8]
}
listSecondaryQualification.append(indQualification)
# qualification[quid[0]] = indQualification
# print(qualification)
for esdid in examscore:
if userid[0]== esdid[2]:
indExamscores = {
'examScoreDetailId': esdid[0],
'attemptedCount': esdid[1],
'candidateId': esdid[2],
'examDate': esdid[3],
'examId': esdid[4],
'examTotalScore': esdid[5],
'examType': esdid[6],
'katExamEventId': esdid[7],
'rightAttempted': esdid[8],
'rptVisStatus': esdid[9],
'scorePercent': esdid[10],
'timeDate': str(esdid[11]),
'token': esdid[12],
'totalQuestion': esdid[13],
'totalScore': esdid[14]
}
listExamScores.append(indExamscores)
# examscores[esdid[0]]=indExamscores
# print(examscores)
for scid in sectionalScore:
if userid[0]== scid[2]:
indSectionalscores = {
'katScoreId': scid[0],
'attemptedCount': scid[1],
'candidateId': scid[2],
'examScoreId': scid[3],
'examTime': scid[4],
'examTitleId': scid[5],
'katExamId': scid[6],
'rightAttempted': scid[7],
'score': scid[8],
'scorePercent': scid[9],
'scoreS3Key': scid[10],
'timeDate': str(scid[11]),
'totalQuestion': scid[12],
'totalScore': scid[13]
}
listSectionalScores.append(indSectionalscores)
# sectionalscores[scid[0]]=indSectionalscores
# print(sectionalscores)
for prid in proejctDetails:
if userid[0] == prid[16]:
indvidualProjectdetail = {
'id': prid[0],
'clientName': prid[1],
'designation': prid[2],
'durationEndMonth': prid[3],
'durationEndYear': prid[4],
'durationStartMonth': prid[5],
'durationStartYear': prid[6],
'employmentNature': prid[7],
'location': prid[8],
'projectDetails': prid[9],
'rolesResponsibilities': prid[10],
'site': prid[11],
'skillsUsed': prid[12],
'teamSize': prid[13],
'timeDate': str(prid[14]),
'title': prid[15],
'userId': prid[16]
}
listProjectDetails.append(indvidualProjectdetail)
# proejctdetail[prid[0]]=indvidualProjectdetail
# print(proejctdetail)
for userempid in employmentDetails:
if userid[0]==userempid[12]:
indEmploymentDetail = {
'id': userempid[0],
'companyName': userempid[1],
'designation': userempid[2],
'durationEndMonth': userempid[3],
'durationEndYear': userempid[4],
'durationStartMonth': userempid[5],
'durationStartYear': userempid[6],
'employmentStatus': userempid[7],
'isCurrent': userempid[8],
'jobProfile': userempid[9],
'location': userempid[10],
'timeDate': str(userempid[11]),
'userId': userempid[12]
}
listEmploymentDetails.append(indEmploymentDetail)
# employmentDetail[userempid[0]]=indEmploymentDetail
# print(employmentDetail)
# for item in listSecondaryQualification:
# jsonSecondaryQualification += json.dumps(item) + ','
# jsonSecondaryQualification = jsonSecondaryQualification[:-1]
#
# for item in listEmploymentDetails:
# jsonEmploymentDetails+=json.dumps(item)+','
# jsonEmploymentDetails = jsonEmploymentDetails[:-1]
#
# for item in listExamScores:
# jsonExamScores+=json.dumps(item)+','
# jsonExamScores = jsonExamScores[:-1]
#
# for item in listProjectDetails:
# jsonProjectDetails+=json.dumps(item)+','
# jsonProjectDetails=jsonProjectDetails[:-1]
#
# for item in listSectionalScores:
# jsonSectionalScores+=json.dumps(item)+','
# jsonSectionalScores=jsonSectionalScores[:-1]
userdata['qualification'] = listSecondaryQualification
userdata['examscores'] = listExamScores
userdata['sectionalscores'] = listSectionalScores
userdata['projectdetail'] = listProjectDetails
userdata['employmentDetail'] = listEmploymentDetails
indexdata["_source"] = userdata
# doc['doc'] = indexdata
data.append(indexdata)
# print(data)
# break
#Flusing All lists
listSecondaryQualification = []
listExamScores = []
listSectionalScores = []
listProjectDetails = []
listEmploymentDetails = []
# jsonSecondaryQualification = ''
# jsonExamScores = ''
# jsonSectionalScores = ''
# jsonProjectDetails = ''
# jsonEmploymentDetails = ''
# proejctdetail = {}
# qualification = {}
# sectionalscores = {}
# examscores = {}
# employmentDetail = {}
# print("Document Inserted Successfully")
if (count==2000):
break
print('On my way')
helpers.bulk(es1, data)
print("bulk import done")

How to use MongoDB $let with Spring-Data?

I have a MongoDB collection of places. A typical place has most of the following fields:
{
"_id" : ObjectId("575014dc6b028f07bef53681"),
"_class" : "domain.model.PlaceV1",
"name" : "Γιασεμί",
"primary_photo_url" : "https://irs0.4sqi.net/img/general/original/34666238_STHSh6CHiC7hpAuB4rztRVg6cFc5ylfi15aRaR7zUuQ.jpg",
"seenDetails" : NumberLong(0),
"foursquare_checkins" : 646,
"foursquare_tips" : 28,
"keywords" : [
""
],
"verified" : 1,
"location" : {
"loc" : {
"type" : "Point",
"coordinates" : [
25.898318,
36.831486
]
},
"formattedAddress" : "Χώρα",
"locality" : "Amorgos",
"first_neighbourhood" : "Katapola",
"greek_locality" : "Αμοργός",
"greek_first_neighbourhood" : "Κατάπολα"
},
"contact" : {
"phone_numbers" : [
"+30 2285 074017"
]
},
"price" : {
"priceVotes" : NumberLong(0),
"price" : 0,
"priceVotesSum" : NumberLong(0)
},
"rating" : {
"rating" : 8,
"ratingVotes" : NumberLong(0),
"ratingVotesSum" : NumberLong(0)
},
"categories" : [
{
"cat_id" : NumberLong(10310061000),
"category" : "Café",
"greek_category" : "Καφετέρια",
"weight" : 4
},
{
"cat_id" : NumberLong(11610021000),
"category" : "Bar",
"greek_category" : "Μπαρ",
"weight" : 4
}
]
}
I want to make queries where the sorting will be based on a score that is a result of some expressions and conditions. From the mongo shell I have tried this:
db.place.aggregate([
{$match:{"location.locality":"Athens"}},
{$project:
{name:1, location:1, score:{
$let: {
vars:{ foursquare: {
$cond: { if: { $gte: [ "$foursquare_checkins", 500 ] }, then: 500, else: "$foursquare_checkins" }
},
rating: {$multiply:["$rating.rating", 100]},
},
in:{$add:["$$foursquare", "$$rating", "$seenDetails"]}
}
}
}
},
{$sort: {score: -1}}]).pretty();
This is a simple example of my queries. The score will contain more complex expressions like the distance from a location. The problem is that I cannot find a way to use the $let and the $cond operator in my Java code with Spring. Could anybody help?
You should be able to do this using nested DBObject and a Custom Aggregation Operation.
For Example:
Map operations = new HashMap();
operations.put("name", 1);
operations.put("location", 1);
operations.put("score", new BasicDBObject("$let", new BasicDBObject("vars", new BasicDBObject())));
Then you can create a CustomAggregationOperation to add this to your project
CustomAggregationOperation project = new CustomAggregationOperation(new BasicDBObject("$project", operation));
This will give you the following pipeline:
{ "$project" : { "score" : { "$let" : { "vars" : { }}} , "name" : 1 , "location" : 1}}
Then you can add your other stages:
Aggregation aggregate = Aggregation.newAggregation(match, project, sort);
public class CustomAggregationOperation implements AggregationOperation {
private DBObject operation;
public CustomAggregationOperation (DBObject operation) {
this.operation = operation;
}
#Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}

Categories

Resources