I am trying to filter by fields that are not exists in my elasticsearch database
here is my fields :
{
"_index" : "catalogue",
"_type" : "_doc",
"_id" : "0lzS2HEB-X5mOkOYpdV9",
"_score" : 1.0,
"_source" : {
"nom" : "Junk Resin Necklace",
"categorie" : "Jewellery",
"image" : "http://img6a.flixcart.com/image/necklace-chain/f/7/g/junk-n-055-junk-necklace-original-imae4cgmqcz4hzzx.jpeg",
"marque" : "Junk"
}
and here is my json file based on NLU output:
{
"intent": {
"name": "Bonbons",
"confidence": 0.9993242025375366
},
"entities": [
{
"entity": "gout",
"start": 26,
"end": 39,
"extractor": "DIETClassifier",
"value": "Eucalyptus"
},
{
"entity": "marque",
"start": 40,
"end": 47,
"extractor": "DIETClassifier",
"value": "RICOLA",
"processors": [
"EntitySynonymMapper"
]
}
],
"intent_ranking": [
{
"name": "Bonbons",
"confidence": 0.9993242025375366
},
{
"name": "greet",
"confidence": 0.0006757942610420287
}
],
"response_selector": {
"default": {
"response": {
"name": null,
"confidence": 0.0
},
"ranking": [],
"full_retrieval_intent": null
}
},
"text": "je veux acheter un bonbon cerise & cola TIC TAC"
}
I tried this:
es=Elasticsearch([{'host':'localhost','port':'9200'}])
variable=json_files['entities']
text=json_files['text']
entities=[]
for i in variable:
query_search={'query':{'match':{i['entity']:i['value']}}}
entities.append(i['entity'])
if(("marque" in entities) and ("categorie" in entities) and ("nom" in entities) and ("image" in entities)):
if(i['entity']=="marque"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="nom"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="categorie"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="image"):
res = es.search(index="catalogue", body=query_search)
print(res)
else:
print("*******")
elif(("marque" in entities) or ("categorie" in entities) or ("nom" in entities)):
if(i['entity']=="marque" and i['entity']!="nom" and i['entity']!="categorie" and i['entity']!="image"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="nom" and i['entity']!="marque" and i['entity']!="categorie" and i['entity']!="image"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="categorie" and i['entity']!="nom" and i['entity']!="marque" and i['entity']!="image"):
res = es.search(index="catalogue", body=query_search)
print(res)
elif(i["entity"]=="image" and i['entity']!="nom" and i['entity']!="categorie" and i['entity']!="marque"):
res = es.search(index="catalogue", body=query_search)
print(res)
else:
res = es.search(index="catalogue", body=query_search)
print(res)
else:
res = es.search(index="catalogue", body=query_search)
print(res)
and the result is :
{
"took":13,
"timed_out":False,
"_shards":{
"total":1,
"successful":1,
"skipped":0,
"failed":0
},
"hits":{
"total":{
"value":0,
"relation":"eq"
},
"max_score":"None",
"hits":[
]
}
}{
"took":460,
"timed_out":False,
"_shards":{
"total":1,
"successful":1,
"skipped":0,
"failed":0
},
"hits":{
"total":{
"value":8,
"relation":"eq"
},
"max_score":8.775399,
"hits":[
{
"_index":"catalogue",
"_type":"_doc",
"_id":"pV3S2HEB-X5mOkOYwgRP",
"_score":8.775399,
"_source":{
"nom":"Sony HT-GT1 2.1 Home Theatre System",
"categorie":"Home Entertainment",
"image":"http://img6a.flixcart.com/image/home-theatre-system/h/x/z/ht-gt1-sony-original-imaefyb3m3smdcau.jpeg",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"fFzS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Haut-parleur sans fil Sony SRSHG1/BLK Hi-Res - Noir anthracite",
"categorie":"haut-parleurs Bluetooth et sans fil",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"flzS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Mini-cassettes vidéo numériques Sony - DVC - 1 heure",
"categorie":"Accessoires appareil photo",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"f1zS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Haut-parleur sans fil SRS-ZR7",
"categorie":"haut-parleurs Bluetooth et sans fil",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"i1zS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Facade autoradio CD marin Sony MEXM100BT 160W RMS avec Bluetooth (noir) et SiriusXM Ready",
"categorie":"Accessoires électroniques pour voiture",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"jFzS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Haut-parleur portable sans fil Sony SRSXB30/BLK XB30 avec Bluetooth",
"categorie":"haut-parleurs Bluetooth et sans fil",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"jVzS2HEB-X5mOkOYjryo",
"_score":8.775399,
"_source":{
"nom":"Mini-système LBT-GPX555 de Sony avec Bluetooth et NFC",
"categorie":"Accessoires audio et vidéo",
"image":"No image",
"marque":"Sony"
}
},
{
"_index":"catalogue",
"_type":"_doc",
"_id":"LVzS2HEB-X5mOkOYsOgL",
"_score":8.775399,
"_source":{
"nom":"Sony Nh-Aa-B4gn Rechargeable Ni-MH Battery",
"categorie":"Cameras & Accessories",
"image":"http://img6a.flixcart.com/image/rechargeable-battery/rechargeable-ni-mh-battery/y/3/j/sony-nh-aa-b4gn-1100x1100-imaeebadghrwfaa8.jpeg",
"marque":"Sony"
}
}
]
}
}{
"took":0,
"timed_out":False,
"_shards":{
"total":1,
"successful":1,
"skipped":0,
"failed":0
},
"hits":{
"total":{
"value":0,
"relation":"eq"
},
"max_score":"None",
"hits":[
]
}
}{
"took":0,
"timed_out":False,
"_shards":{
"total":1,
"successful":1,
"skipped":0,
"failed":0
},
"hits":{
"total":{
"value":0,
"relation":"eq"
},
"max_score":"None",
"hits":[
]
}
}
how can I filter my query with fields that are not exists in my elasticsearch database (like : gout )and get exactly "bonbon cerise & cola TIC TAC" as a result?
Hi I am having an elastic search index named mep-reports-today. the following shows how it looks.
{
"took": 19,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 100,
"max_score": 1.0,
"hits": [
{
"_index": "mep-reports-today",
"_type": "doc",
"_id": "Rta62G0Bc1ykGt-JpwfK",
"_score": 1.0,
"_source": {
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-09T15:47:48.778Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": "420736408283",
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": "8800111",
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1,
"submission_ts": 1568105380000,
"delivery_ts": 1567491477000,
"campaign_name": "Munchies Ireland Sandwitch and drinks promotion",
"flight_name": "Very Very long long flight"
}
},
{
"_index": "mep-reports-today",
"_type": "doc",
"_id": "SNa62G0Bc1ykGt-JpwfL",
"_score": 1.0,
"_source": {
"inventory": "MMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-01T02:40:42.040Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": "420736408281",
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": "8800111",
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1,
"submission_ts": 1568105380000,
"delivery_ts": 1565902976000,
"campaign_name": "Starbucks Promotion",
"flight_name": "Short Flight"
}
},
{
"_index": "mep-reports-today",
"_type": "doc",
"_id": "Sda62G0Bc1ykGt-JpwfL",
"_score": 1.0,
"_source": {
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-01T16:00:05.666Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": "420736408281",
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": "8800111",
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1,
"submission_ts": 1568105380000,
"delivery_ts": 1558893228000,
"campaign_name": "Starbucks Promotion",
"flight_name": "Very Very long long flight"
}
},
{
"_index": "mep-reports-today",
"_type": "doc",
"_id": "Sta62G0Bc1ykGt-JpwfL",
"_score": 1.0,
"_source": {
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-03T17:09:50.380Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": "420736408281",
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": "8800111",
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1,
"submission_ts": 1568105380000,
"delivery_ts": 1547471597000,
"campaign_name": "Munchies Ireland Sandwitch and drinks promotion",
"flight_name": "Very Very long long flight"
}
},
{
"_index": "mep-reports-today",
"_type": "doc",
"_id": "Tta62G0Bc1ykGt-JpwfL",
"_score": 1.0,
"_source": {
"inventory": "SMS",
"msg_text": "This is random text",
"status": "ENROUTE",
"#timestamp": "2019-09-09T21:46:14.947Z",
"o_error": "",
"flight_id": "92348fa1-ca6c-456a-b3b2-85fba2d2deed",
"recipient": "420736408283",
"account_id": "a56f7e14-20f9-40e6-90c6-10604140ac5f",
"sender": "8800111",
"campaign_id": "6f2abca3-b46d-43f3-91be-3278a8dd7dc0",
"nof_segments": 1,
"#version": 1,
"submission_ts": 1568105380000,
"delivery_ts": 1559378049000,
"campaign_name": "Munchies Ireland Sandwitch and drinks promotion",
"flight_name": "Short Flight"
}
}
]
}
}
I have a search screen where the user can search on different fields like #timestamp, status, campaign_id, recipient , inventory, flight_id, account_id. I am using an java elastic search client to issue search request to the elastic search. However it is not working as expected when i need to search on status and inventory field. The status and inventory are presented as multi select option to the user .
so here is how i build the query.
#Repository
public class MessageHistoryReportingRepository {
public MessageHistorySearchResponse findAll(MessageHistoryFilterRequest messageHistoryFilterRequest) {
SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(ELASTIC_SEARCH_INDEX);
SearchRequest searchRequest = searchRequestBuilder.from(messageHistoryFilterRequest.getPageNumber())
.size(messageHistoryFilterRequest.getPageSize()).timeout(300, TimeUnit.SECONDS)
.range(messageHistoryFilterRequest.getStartDate(), messageHistoryFilterRequest.getEndDate())
.msisdn(messageHistoryFilterRequest.getMsisdn()).accountId(messageHistoryFilterRequest.getAccountId())
.campaignId(messageHistoryFilterRequest.getCampaignId())
.flightId(messageHistoryFilterRequest.getFlightId())
.cdrStatus(messageHistoryFilterRequest.getCdrStatus())
.inventoryCode(messageHistoryFilterRequest.getInventoryCode()).sort().build();
SearchResponse searchResponse = null;
List<MessageHistory> messageHistories = null;
try {
searchResponse = elasticSearchClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
List<SearchHit> searchHitResults = Arrays.asList(searchHits.getHits());
messageHistories = searchHitResults.stream().map(this::translate).collect(Collectors.toList());
return new MessageHistorySearchResponse(messageHistories, messageHistoryFilterRequest.getPageSize(),
messageHistoryFilterRequest.getPageNumber(), searchHits.getTotalHits());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static class SearchRequestBuilder {
private SearchRequest searchRequest;
private SearchSourceBuilder searchSourceBuilder;
private BoolQueryBuilder boolQueryBuilder;
SearchRequestBuilder(String elasticSearchIndex) {
this.searchRequest = new SearchRequest(elasticSearchIndex);
this.searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());
this.searchSourceBuilder = new SearchSourceBuilder();
this.searchRequest.source(searchSourceBuilder);
this.boolQueryBuilder = QueryBuilders.boolQuery();
this.searchSourceBuilder.query(this.boolQueryBuilder);
}
SearchRequestBuilder from(Integer pageNumber) {
this.searchSourceBuilder.from(pageNumber);
return this;
}
SearchRequestBuilder size(Integer pageSize) {
this.searchSourceBuilder.size(pageSize);
return this;
}
SearchRequestBuilder timeout(long duration, TimeUnit timeUnit) {
this.searchSourceBuilder.timeout(new TimeValue(duration, TimeUnit.SECONDS));
return this;
}
SearchRequestBuilder range(ZonedDateTime startDate, ZonedDateTime endDate) {
RangeQueryBuilder startRangeQueryBuilder = QueryBuilders.rangeQuery("#timestamp").gte(startDate);
startRangeQueryBuilder.format("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
boolQueryBuilder.must(startRangeQueryBuilder);
RangeQueryBuilder endRangeQueryBuilder = QueryBuilders.rangeQuery("#timestamp").lte(endDate.plusDays(1l));
boolQueryBuilder.must(endRangeQueryBuilder);
endRangeQueryBuilder.format("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return this;
}
SearchRequestBuilder msisdn(String msisdn) {
if (msisdn != null) {
if (msisdn.indexOf("*") >= 0) {
WildcardQueryBuilder msisdnWildCardQueryBuilder = new WildcardQueryBuilder("recipient", msisdn);
boolQueryBuilder.must(msisdnWildCardQueryBuilder);
} else {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("recipient", msisdn);
boolQueryBuilder.must(matchQueryBuilder);
}
}
return this;
}
SearchRequestBuilder accountId(UUID accountId) {
if (accountId != null) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("account_id", accountId.toString());
boolQueryBuilder.must(matchQueryBuilder);
}
return this;
}
SearchRequestBuilder campaignId(UUID campaignId) {
if (campaignId != null) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("campaign_id", campaignId.toString());
boolQueryBuilder.must(matchQueryBuilder);
}
return this;
}
SearchRequestBuilder flightId(UUID flightId) {
if (flightId != null) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("flight_id", flightId.toString());
boolQueryBuilder.must(matchQueryBuilder);
}
return this;
}
SearchRequestBuilder cdrStatus(List<String> cdrStatus) {
if (cdrStatus != null && cdrStatus.size() > 0) {
for(String cdrStatusCode:cdrStatus) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("status", cdrStatusCode);
boolQueryBuilder.should(matchQueryBuilder);
}
}
return this;
}
SearchRequestBuilder inventoryCode(List<String> inventoryCode) {
if (inventoryCode != null && inventoryCode.size() > 0) {
for(String inventoryCodeValue:inventoryCode) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("inventory", inventoryCodeValue);
boolQueryBuilder.should(matchQueryBuilder);
}
}
// if (inventoryCode != null) {
// MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("inventory", inventoryCode);
// boolQueryBuilder.must(matchQueryBuilder);
// }
return this;
}
SearchRequestBuilder sort() {
searchSourceBuilder.sort(new FieldSortBuilder("#timestamp").order(SortOrder.DESC));
return this;
}
SearchRequestBuilder scroll(TimeValue value) {
searchRequest.scroll(new Scroll(value));
return this;
}
SearchRequestBuilder fetchSourceContext(boolean fetchSource, String[] includes, String[] excludes) {
FetchSourceContext fetchContext = new FetchSourceContext(fetchSource, includes, excludes);
this.searchSourceBuilder.fetchSource(fetchContext);
return this;
}
SearchRequest build() {
return this.searchRequest;
}
}
}
what i am trying to achieve is to do is and condition based on the user inputs as mentioned below.
#timestamp > (input start date ) and #timestamp < (input end date) and campaign_id = 6f2abca3-b46d-43f3-91be-3278a8dd7dc0 and recipient = "420736408283" and inventory in ( 'SMS', 'MMS') and status in ( 'ENROUTE' , 'DELIVERED').
however it is not working because of the multi select of inventory and status fields. any idea how can i rewrite my SearchRequestBuilder class.
SearchRequestBuilder cdrStatus(List<String> cdrStatus) {
if (cdrStatus != null && cdrStatus.size() > 0) {
for(String cdrStatusCode:cdrStatus) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("status", cdrStatusCode);
boolQueryBuilder.should(matchQueryBuilder);
}
}
return this;
}
SearchRequestBuilder inventoryCode(List<String> inventoryCode) {
if (inventoryCode != null && inventoryCode.size() > 0) {
for(String inventoryCodeValue:inventoryCode) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("inventory", inventoryCodeValue);
boolQueryBuilder.should(matchQueryBuilder);
}
}
// if (inventoryCode != null) {
// MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("inventory", inventoryCode);
// boolQueryBuilder.must(matchQueryBuilder);
// }
return this;
}
thank you so much
Replace this
for(String inventoryCodeValue:inventoryCode) {
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("inventory", inventoryCodeValue);
boolQueryBuilder.should(matchQueryBuilder);
}
with this,
TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder("inventory",inventoryCode);
boolQueryBuilder.should(termsQueryBuilder);
Similar change goes for cdrStatus
I find the accepted answer to get currencycode from country code in objective c here - How to get ISOCurrencyCode from a ISOCountryCode in iphone sdk?
Can someone help with the swift code to do the same ?
let components: [String: String] = [NSLocaleCountryCode: "CA"]
let identifier = NSLocale.localeIdentifierFromComponents(components)
let locale = NSLocale(localeIdentifier: identifier)
let currencyCode = locale.objectForKey(NSLocaleCurrencyCode)
print(currencyCode)
public static func convertStringCurrencyToNumber(strCurrency:String, locale:String)->Double {
var formatter = NSNumberFormatter()
formatter.currencyCode = locale
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
if let converted:Double = formatter.numberFromString(strCurrency)?.doubleValue {
return converted
}else{
return 0.0
}
}
Changing formatter.locale to formatter.currencyCode works as expected with the ISO 4127 Country and Currency code "USD".
Use below this return type function to get country_code:-
//MARK:- GET COUNTRY CODE
func getCountryPhonceCode (_ country : String) -> String
{
let x : [String] = ["972", "IL",
"93" , "AF",
"355", "AL",
"213", "DZ",
"1" , "AS",
"376", "AD",
"244", "AO",
"1" , "AI",
"1" , "AG",
"54" , "AR",
"374", "AM",
"297", "AW",
"61" , "AU",
"43" , "AT",
"994", "AZ",
"1" , "BS",
"973", "BH",
"880", "BD",
"1" , "BB",
"375", "BY",
"32" , "BE",
"501", "BZ",
"229", "BJ",
"1" , "BM",
"975", "BT",
"387", "BA",
"267", "BW",
"55" , "BR",
"246", "IO",
"359", "BG",
"226", "BF",
"257", "BI",
"855", "KH",
"237", "CM",
"1" , "CA",
"238", "CV",
"345", "KY",
"236", "CF",
"235", "TD",
"56", "CL",
"86", "CN",
"61", "CX",
"57", "CO",
"269", "KM",
"242", "CG",
"682", "CK",
"506", "CR",
"385", "HR",
"53" , "CU" ,
"537", "CY",
"420", "CZ",
"45" , "DK" ,
"253", "DJ",
"1" , "DM",
"1" , "DO",
"593", "EC",
"20" , "EG" ,
"503", "SV",
"240", "GQ",
"291", "ER",
"372", "EE",
"251", "ET",
"298", "FO",
"679", "FJ",
"358", "FI",
"33" , "FR",
"594", "GF",
"689", "PF",
"241", "GA",
"220", "GM",
"995", "GE",
"49" , "DE",
"233", "GH",
"350", "GI",
"30" , "GR",
"299", "GL",
"1" , "GD",
"590", "GP",
"1" , "GU",
"502", "GT",
"224", "GN",
"245", "GW",
"595", "GY",
"509", "HT",
"504", "HN",
"36" , "HU",
"354", "IS",
"91" , "IN",
"62" , "ID",
"964", "IQ",
"353", "IE",
"972", "IL",
"39" , "IT",
"1" , "JM",
"81", "JP", "962", "JO", "77", "KZ",
"254", "KE", "686", "KI", "965", "KW", "996", "KG",
"371", "LV", "961", "LB", "266", "LS", "231", "LR",
"423", "LI", "370", "LT", "352", "LU", "261", "MG",
"265", "MW", "60", "MY", "960", "MV", "223", "ML",
"356", "MT", "692", "MH", "596", "MQ", "222", "MR",
"230", "MU", "262", "YT", "52","MX", "377", "MC",
"976", "MN", "382", "ME", "1", "MS", "212", "MA",
"95", "MM", "264", "NA", "674", "NR", "977", "NP",
"31", "NL", "599", "AN", "687", "NC", "64", "NZ",
"505", "NI", "227", "NE", "234", "NG", "683", "NU",
"672", "NF", "1", "MP", "47", "NO", "968", "OM",
"92", "PK", "680", "PW", "507", "PA", "675", "PG",
"595", "PY", "51", "PE", "63", "PH", "48", "PL",
"351", "PT", "1", "PR", "974", "QA", "40", "RO",
"250", "RW", "685", "WS", "378", "SM", "966", "SA",
"221", "SN", "381", "RS", "248", "SC", "232", "SL",
"65", "SG", "421", "SK", "386", "SI", "677", "SB",
"27", "ZA", "500", "GS", "34", "ES", "94", "LK",
"249", "SD", "597", "SR", "268", "SZ", "46", "SE",
"41", "CH", "992", "TJ", "66", "TH", "228", "TG",
"690", "TK", "676", "TO", "1", "TT", "216", "TN",
"90", "TR", "993", "TM", "1", "TC", "688", "TV",
"256", "UG", "380", "UA", "971", "AE", "44", "GB",
"1", "US", "598", "UY", "998", "UZ", "678", "VU",
"681", "WF", "967", "YE", "260", "ZM", "263", "ZW",
"591", "BO", "673", "BN", "61", "CC", "243", "CD",
"225", "CI", "500", "FK", "44", "GG", "379", "VA",
"852", "HK", "98", "IR", "44", "IM", "44", "JE",
"850", "KP", "82", "KR", "856", "LA", "218", "LY",
"853", "MO", "389", "MK", "691", "FM", "373", "MD",
"258", "MZ", "970", "PS", "872", "PN", "262", "RE",
"7", "RU", "590", "BL", "290", "SH", "1", "KN",
"1", "LC", "590", "MF", "508", "PM", "1", "VC",
"239", "ST", "252", "SO", "47", "SJ",
"963","SY",
"886",
"TW", "255",
"TZ", "670",
"TL","58",
"VE","84",
"VN",
"284", "VG",
"340", "VI",
"678","VU",
"681","WF",
"685","WS",
"967","YE",
"262","YT",
"27","ZA",
"260","ZM",
"263","ZW"]
var keys = [String]()
var values = [String]()
let whitespace = CharacterSet.decimalDigits
//let range = phrase.rangeOfCharacterFromSet(whitespace)
for i in x {
// range will be nil if no whitespace is found
if (i.rangeOfCharacter(from: whitespace) != nil) {
values.append(i)
}
else {
keys.append(i)
}
}
let countryCodeListDict = NSDictionary(objects: values as [String], forKeys: keys as [String] as [NSCopying])
if let t: AnyObject = (countryCodeListDict as? [String : AnyObject])? [country] {
return countryCodeListDict[country] as! String
} else
{
return ""
}
}
I'm new to corePlot and i'm having trouble to plot the graph(Line) dynamically from json when we select a particular row in UIPickerView.
Here,
Line graph with x-axis: Time as 02,03,04,.....
y-axis: temperature as 10,20,30,.....
UIPickerView consists of Date(s). for eg: we have 3 rows :
06-03-2015, 07-03-2015, 08-03-2015
and now if we select any particular row in UIPickerView i have to display line graph. I have done with Static data but now i'm getting trouble with dynamic data.
-(void)initialisePlot
{
// Start with some simple sanity checks before we kick off
if ( (self.hostingView == nil) || (self.graphData == nil) ) {
NSLog(#"TUTSimpleScatterPlot: Cannot initialise plot without hosting view or data.");
return;
}
if ( self.graph != nil ) {
NSLog(#"TUTSimpleScatterPlot: Graph object already exists.");
return;
}
// Create a graph object which we will use to host just one scatter plot.
CGRect frame = [self.hostingView bounds];
//CGRect frame = [self.hostingView bounds];
//CGRect frame = [self.hostingView frame];
self.graph = [[CPTXYGraph alloc] initWithFrame:frame] ;
//self.hostingView=[[CPTGraphHostingView alloc]initWithFrame:CGRectMake(0.0, 0.0, 900.0, 420.0)];
//self.graph = [[CPTXYGraph alloc] initWithFrame:self.hostingView.bounds];
// Add some padding to the graph, with more at the bottom for axis labels.
self.graph.plotAreaFrame.paddingTop = 20.0f;
self.graph.plotAreaFrame.paddingRight = 10.0f;
self.graph.plotAreaFrame.paddingBottom = 50.0f;
self.graph.plotAreaFrame.paddingLeft = 60.0f;
// Tie the graph we've created with the hosting view.
self.hostingView.hostedGraph = self.graph;
// If you want to use one of the default themes - apply that here.
[self.graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
// Create a line style that we will apply to the axis and data line.
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 2.0f;
// Create a text style that we will use for the axis labels.
CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
textStyle.fontName = #"Helvetica";
textStyle.fontSize = 14;
textStyle.color = [CPTColor whiteColor];
// Create the plot symbol we're going to use.
CPTPlotSymbol *plotSymbol = [CPTPlotSymbol crossPlotSymbol];
plotSymbol.lineStyle = lineStyle;
plotSymbol.size = CGSizeMake(8.0, 8.0);
// Setup some floats that represent the min/max values on our axis.
int xAxisMin = 0;
int xAxisMax = 20;
float yAxisMin = 0;
float yAxisMax = 50;
// We modify the graph's plot space to setup the axis' min / max values.
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(xAxisMin) length:CPTDecimalFromInt(xAxisMax-xAxisMin)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yAxisMin) length:CPTDecimalFromFloat(yAxisMax - yAxisMin)];
// Modify the graph's axis with a label, line style, etc.
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.title = #"Time";
axisSet.xAxis.titleTextStyle = textStyle;
axisSet.xAxis.titleOffset = 20;
axisSet.xAxis.axisLineStyle = lineStyle;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.labelTextStyle = textStyle;
axisSet.xAxis.labelOffset = 3;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(2);
axisSet.xAxis.minorTicksPerInterval = 1;
axisSet.xAxis.minorTickLength = 5;
axisSet.xAxis.majorTickLength = 7;
axisSet.yAxis.title = #"Temperature";
axisSet.yAxis.titleTextStyle = textStyle;
axisSet.yAxis.titleOffset = 40.0f;
axisSet.yAxis.axisLineStyle = lineStyle;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.labelTextStyle = textStyle;
axisSet.yAxis.labelOffset = 3.0f;
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(10.0f);
axisSet.yAxis.minorTicksPerInterval = 1;
axisSet.yAxis.minorTickLength = 5.0f;
axisSet.yAxis.majorTickLength = 7.0f;
// Add a plot to our graph and axis. We give it an identifier so that we
// could add multiple plots (data lines) to the same graph if necessary.
CPTScatterPlot *plot = [[CPTScatterPlot alloc] init] ;
plot.dataSource = self;
plot.identifier = #"mainplot";
plot.dataLineStyle = lineStyle;
plot.plotSymbol = plotSymbol;
[self.graph addPlot:plot];
}
// Delegate method that returns the number of points on the plot
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"mainplot"] )
{
return [self.graphData count];
}
return 0;
}
// Delegate method that returns a single X or Y value for a given plot.
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"mainplot"] )
{
NSValue *value = [self.graphData objectAtIndex:index];
CGPoint point = [value CGPointValue];
// FieldEnum determines if we return an X or Y value.
if ( fieldEnum == CPTScatterPlotFieldX )
{
return [NSNumber numberWithInt:point.x];
}
else // Y-Axis
{
return [NSNumber numberWithFloat:point.y];
}
}
return [NSNumber numberWithFloat:0];
}
In viewDidLoad i'm calling this method as follows:
pickerData=[[NSArray alloc]initWithObjects:#"28-02-2015",#"01-03-2015",#"02-03-2015",#"03-03-2015",#"04-03-2015", nil];
NSMutableArray *data1 = [NSMutableArray array];
[data1 addObject:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:data1];
[self.scatterPlot initialisePlot];
pickerView datasource and delegate methods as follows with dynamic data:
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return pickerData.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return pickerData[row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//PickerModal *pModal=[picDataArray objectAtIndex:row];
pickObj=[picDataArray objectAtIndex:row];
//result=[NSString stringWithFormat:#"%#",pickObj.picDate];
NSLog(#"time :%#",pickObj.picTime);
NSLog(#"temp :%#",pickObj.picTemperature);
for (int i=0; i<50; i++) {
int selectedRow=[self.myPickerView selectedRowInComponent:0];
if ((selectedRow=i)) {
NSMutableArray *data1 = [NSMutableArray array];
[data1 addObject:[NSValue valueWithCGPoint:CGPointMake([pickObj.picTime floatValue], [pickObj.picTemperature floatValue])]];
NSMutableArray *arr=[[NSMutableArray alloc]initWithArray:data1];
self.scatterPlot = [[TUTSimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:arr];
[self.scatterPlot initialisePlot];
}
}
[pickerView reloadComponent:0];
}
i'm parsing json data as :
-(void)retrieveData{
NSString *sensorTagID=#"UIUIA6767672345678910987654321";
NSMutableString *globalUrlString=[NSMutableString stringWithString:#"url"];
[globalUrlString appendString:[NSString stringWithFormat:#"?SensorTagID=%#",sensorTagID]];
NSLog(#"url string:%#",globalUrlString);
NSURL *url=[NSURL URLWithString:globalUrlString];
NSMutableURLRequest *globalRequest=[NSMutableURLRequest requestWithURL:[url standardizedURL]];
[globalRequest setHTTPMethod:#"GET"];
NSError *error = nil;
NSURLResponse *theResponse = [[NSURLResponse alloc]init];
//connecting to the server
NSData *data = [NSURLConnection sendSynchronousRequest:globalRequest returningResponse:&theResponse error:&error];
//NSData *data=[NSData dataWithContentsOfURL:url];
json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
picDataArray=[[NSMutableArray alloc]init];
for (int i=0; i<json.count; i++) {
pickDate=[[json objectAtIndex:i]valueForKey:#"Date"];
NSLog(#"date %#",pickDate);
NSArray *getEvents=[[json objectAtIndex:i]valueForKey:#"OnDateSensorValues"];
for (NSDictionary *eventsObj in getEvents) {
pickHumidity=eventsObj[#"Humidity"];
//NSLog(#"humidity %#",pickHumidity);
pickLocationHumidity=eventsObj[#"LocationHumidity"];
//NSLog(#"locHumidity %#",pickLocationHumidity);
pickLocationTemperature=eventsObj[#"LocationTemperature"];
//NSLog(#"locTemp %#",pickLocationTemperature);
pickTemperature=eventsObj[#"Temperature"];
NSLog(#"temp %#",pickTemperature);
pickTime=eventsObj[#"Time"];
NSLog(#"time %#",pickTime);
}
pickObj=[[PickerModal alloc]initWithPicDate:pickDate andPicHumidity:pickHumidity andPicLocationHumidity:pickLocationHumidity andPicLocationTemperature:pickLocationTemperature andPicTemperature:pickTemperature andPicTime:pickTime];
[picDataArray addObject:pickObj];
}
[self.myPickerView reloadComponent:0];
}
json output as follows:
[
{
"Date": "2015-02-26",
"OnDateSensorValues": [
{
"Humidity": "49",
"LocationHumidity": "49",
"LocationTemperature": "45",
"Temperature": "45",
"Time": "10"
},
{
"Humidity": "48",
"LocationHumidity": "48",
"LocationTemperature": "44",
"Temperature": "44",
"Time": "11"
},
{
"Humidity": "47",
"LocationHumidity": "47",
"LocationTemperature": "43",
"Temperature": "43",
"Time": "12"
},
{
"Humidity": "46",
"LocationHumidity": "46",
"LocationTemperature": "42",
"Temperature": "42",
"Time": "13"
},
{
"Humidity": "45",
"LocationHumidity": "45",
"LocationTemperature": "41",
"Temperature": "41",
"Time": "14"
}
]
},
{
"Date": "2015-02-27",
"OnDateSensorValues": [
{
"Humidity": "29",
"LocationHumidity": "29",
"LocationTemperature": "25",
"Temperature": "25",
"Time": "6"
},
{
"Humidity": "28",
"LocationHumidity": "28",
"LocationTemperature": "24",
"Temperature": "24",
"Time": "7"
},
{
"Humidity": "27",
"LocationHumidity": "27",
"LocationTemperature": "23",
"Temperature": "23",
"Time": "8"
},
{
"Humidity": "26",
"LocationHumidity": "26",
"LocationTemperature": "22",
"Temperature": "22",
"Time": "9"
},
{
"Humidity": "25",
"LocationHumidity": "25",
"LocationTemperature": "21",
"Temperature": "21",
"Time": "10"
}
]
},
{
"Date": "2015-02-28",
"OnDateSensorValues": [
{
"Humidity": "31",
"LocationHumidity": "31",
"LocationTemperature": "35",
"Temperature": "35",
"Time": "22"
},
{
"Humidity": "32",
"LocationHumidity": "32",
"LocationTemperature": "36",
"Temperature": "36",
"Time": "21"
},
{
"Humidity": "33",
"LocationHumidity": "33",
"LocationTemperature": "37",
"Temperature": "37",
"Time": "20"
},
{
"Humidity": "34",
"LocationHumidity": "34",
"LocationTemperature": "38",
"Temperature": "38",
"Time": "19"
},
{
"Humidity": "35",
"LocationHumidity": "35",
"LocationTemperature": "39",
"Temperature": "39",
"Time": "18"
}
]
},
{
"Date": "2015-03-01",
"OnDateSensorValues": [
{
"Humidity": "12",
"LocationHumidity": "12",
"LocationTemperature": "16",
"Temperature": "16",
"Time": "2"
},
{
"Humidity": "13",
"LocationHumidity": "13",
"LocationTemperature": "17",
"Temperature": "17",
"Time": "1"
},
{
"Humidity": "14",
"LocationHumidity": "14",
"LocationTemperature": "18",
"Temperature": "18",
"Time": "2"
},
{
"Humidity": "15",
"LocationHumidity": "15",
"LocationTemperature": "19",
"Temperature": "19",
"Time": "3"
},
{
"Humidity": "16",
"LocationHumidity": "16",
"LocationTemperature": "20",
"Temperature": "20",
"Time": "4"
}
]
},
{
"Date": "2015-03-02",
"OnDateSensorValues": [
{
"Humidity": "32",
"LocationHumidity": "32",
"LocationTemperature": "36",
"Temperature": "36",
"Time": "20"
},
{
"Humidity": "33",
"LocationHumidity": "33",
"LocationTemperature": "37",
"Temperature": "37",
"Time": "21"
},
{
"Humidity": "34",
"LocationHumidity": "34",
"LocationTemperature": "38",
"Temperature": "38",
"Time": "22"
},
{
"Humidity": "35",
"LocationHumidity": "35",
"LocationTemperature": "39",
"Temperature": "39",
"Time": "23"
},
{
"Humidity": "36",
"LocationHumidity": "36",
"LocationTemperature": "40",
"Temperature": "40",
"Time": "24"
}
]
}
]
from here i would like to take temp,time values and show on graph. But i'm able to plot only one point on the graph. How to get all time and temp values on the graph?....Please help me as i'm struggling with the concept since 1week.