I have saved latitudes and longitudes for my points as Geography typed. I created custom api and I am able to retrieve points from closest by this code:
exports.get = function(request, response) {
var lat = request.query.latitude.replace(",",".");
var lng = request.query.longitude.replace(",",".");
var limit = +request.query.limit;
if (!limit) limit = 20;
console.log('Filtr: lat - %s, lng - %s, limit - %s', lat, lng, limit);
var mssql = request.service.mssql;
var queryString = "SELECT TOP (?) id, title, description, category, city, street, price, startdate, enddate, location.Lat latitude, location.Long longitude, location.STDistance(geography::Point(?, ?, 4326)) AS distance FROM Action ORDER BY distance"
mssql.query(queryString, [limit, lat, lng], {
success: function(results) {
request.respond(statusCodes.OK, results);
}
});
};
But I want to retrieve all points and I can't figure out how to do it. Now when I have just in script operation read:
function read(query, user, request) {
request.execute();
}
I get this in my object:
"location":{
"0":230,
"1":16,
"2":0,
"3":0,
"4":1,
"5":12,
"6":67,
"7":203,
"8":186,
"9":127,
"10":44,
"11":190,
"12":72,
"13":64,
"14":70,
"15":64,
"16":133,
"17":35,
"18":72,
"19":169,
"20":48,
"21":64,
"length":22
},
I was trying to modified sql script from custom api to apply to read operation but I don't know how to change query in read operation script. I was trying to work with success after executing request but It's too late. Anyone can help me with this?
I found solution to my problem:
function read(query, user, request) {
var queryString = "SELECT id, title, description, category, city, street, price, startdate, enddate, location.Lat latitude, location.Long longitude FROM Action";
mssql.query(queryString, {
success: function(results) {
request.respond(statusCodes.OK, results);
}
});
}
I tried this as first option before I asked the question but I tried it with this line:
var mssql = request.service.mssql;
But then I found example without this line and still with mssql object and it's working.
Related
This is how my data is saved inside LiveTracker there is 2,8 which are bus route id and inside it there is auto generated firebase id and inside that id there is latitude and longitude and i wanna access those latitude and longitude but i am stuck at here and dont know how to fetch that data need soo help
This is my data format which i get when i print data
{-NCQE5NU7ajW2L57gt1o: {latitude: -122.07730612330596, longitude: 37.41749912586621}, -NCQF6O3vx2NYVdZKD0X: {latitude: -122.083922, longitude: 37.4214938}, -NCQF6kWJPOyLuymJeXz: {latitude: -122.07730453282453, longitude: 37.417496832888055}, -NCQF5afZXRqg1Heb9Oq: {latitude: -122.07730562660478, longitude: 37.417495975114676}, -NCQDoU67-ZjN4kNEyPr: {latitude: -122.07730474508638, longitude: 37.41749751091001},
this is how i am trying to fetch that latitude and longitude but i am stuck and dont know how to get it
_dbReference?.child("LiveTracker").child(passedId.toString()).onValue.listen((event) {
var data = event.snapshot.value;
print("This is data $data");
/* _markers.add(Marker(
markerId: MarkerId(DateTime.now().toIso8601String()),
position: LatLng(double.parse(event.snapshot.value.toString()),
double.parse(event.snapshot.value.toString()))));*/
});
data appears to be a Map object when you print it. Assuming your app code is aware of the autogenerated IDs, you can fetch latitude and longitude like so:
var data = event.snapshot.value;
var latitude = data['-NCQE5NU7ajW2L57gt1o']['latitude'];
var longitude = data['-NCQE5NU7ajW2L57gt1o']['longitude'];
print("$latitude, $longitude");
If I misunderstood and your issue is not being aware of the auto generated IDs, then you need to either restructure your data or fetch the keys at runtime with: data.keys.toList()
I am searching for plugin from which I can get province and cities for one country only. Mean I dont want to select country.
I have found this plugin which is good but issue is its asking for country pick.
https://pub.dev/packages/restcountries
From the examples at this link
List cities = await api.getCities(
countryCode: 'id', region: 'Jawa Timur', keyword: 'mal');
Since you already know which country you want to get the cities from, just assign that country's code to countryCode,
For example, if you want cities of United States with keyword ar,
List<City> cities = await api.getCities(
countryCode: 'us', keyword: 'ar');
I have to agree with the above answer. Given a County you could make a series of calls to get the data set you want.
countries = await api.getCountries(); -- Will return the countries the service has, then search through the list to find the one you want.
regions = await api.getRegions(countryCode: 'id'); -- Will then get you the regions for the country, I'm assuming you'll get the code from the first call, otherwise a good place to start with the code would be to use the the IEEE country codes.
Check Them Out Here
Finally use the regions you got to get the cities;
await api.getCities(countryCode: 'id', region: 'Jawa Timur');
Bringing it all together you'd have something like this... (I have not looked at the API specification so the guess at a memeber in that loop "region.name" is likely incorrect)
import 'package:restcountries/restcountries.dart';
void main() async {
var api = RestCountries.setup(Platform.environment['API_KEY']);
List<Country> countries;
List<Region> regions;
List<City> cities;
countries = await api.getCountries();
// Search here for your country
regions = await api.getRegions(countryCode: '*YOUR COUNTRY CODE HERE*');
// Now we loop to get cities in every region.
regions.forEach((region){
cities += await api.getCities(countryCode: '*YOUR COUNTRY CODE HERE*', region: region.name);
});
print(regions);
print(cities);
}
I am using the Postgres Package (On the pub.dev site) to UPDATE records in a very simple database. It has two fields: a Text field prime key named number, and a Date field named date_of_birth.
If the date_of_birth is a valid DateTime string then all is well (as can be seen from the code below). But if date_of_birth is unknown (so I set to null) the UPDATE fails:
import 'package:postgres/postgres.dart';
void main() async {
final conn = PostgreSQLConnection(
'localhost',
XXXXX,
'XXXXX',
username: 'XXXXX',
password: 'XXXXX',
);
await conn.open();
DateTime dob = DateTime.now();
var results;
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
await conn.close();
}
If I set:
dob = null;
The program fails with the error:
Unhandled exception:
PostgreSQLSeverity.error 22007: invalid input syntax for type date: "null"
So I need to include a check on the dob field and the program now looks like this:
DateTime dob = DateTime.now();
dob = null;
var results;
if (dob == null) {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = null
WHERE number = '123123'
''');
} else {
results = await conn.query('''
UPDATE account_details
SET date_of_birth = '$dob'
WHERE number = '123123'
''');
}
That works fine for my simple database, but in my real App. I have a number of date fields in one table. So I have to do a check for each possible combination of those date values - writing a code block for each!
Can anyone tell me how I can UPDATE both null and a valid date using a single statement please?
You are quoting the query parameters yourself. NEVER do this. In addition to the sort of problem you have just seen it also leaves you open to a trivial SQL injection attack.
The library you are using will have some way of putting placeholders into the query text and passing variables when executing the query. Use that.
I have a Dapper query as follows
Public void GetAllCusomers(string CustmoerId, StringFirstName, String LastName, String Gender)
{
TblCustomer tblCustomer = new TblCustomer();
using (var sqlConnection = new SqlConnection(“DatabaseConncetionString"))
{
sqlConnection.Open();
//tblCustomer = sqlConnection.Query<TblCustomer >("SELECT * FROM tblCustomer WHERE CustomerId = #CustomerID" AND FirstName = #FirstName……………, new { CustomerID = CustomerId,……………. }).ToList();
tblCustomer = sqlConnection.Query<TblCustomer >("SELECT * FROM tblCustomer WHERE CustomerId = #CustomerID", new { CustomerID = CustomerId }).ToList();
sqlConnection.Close();
}
}
The question is how to build the query? In the above method user can provide value to any parameters that he wishes to query. If the parameter value is blank that will not be used in the WHERE criteria. I will be using all the supplied parameters in the where criteria with AND operations.
Without Dapper it is easy to build the dynamic query by concatenating the SQL statement depending upon the supplied parameters. How to build these queries in Dapper without compromising the parameterized feature.
Thank you,
Ganesh
string sql = "SELECT * FROM tblCustomer " +
"WHERE CustomerId = #CustomerID AND FirstName = #FirstName"; // ...
var parameters = new DynamicParameters();
parameters.Add("CustomerId", customerID);
parameters.Add("FirstName", firstName);
// ...
connection.Execute(sql, parameters);
You would do it similar to how you build a dynamic query. Build your string dynamically (based on user input), only including filters in the Where clause as needed.
Exmpale:
var query = new StringBuilder("select * from users where ");
if(!string.IsNullOrEmpty(firstname)) query.Append("FirstName = #FirstName ");
As far as passing in the parameters, you can either construct an object that includes all of your possible parameters with values to pass in:
new {FirstName = "John", LastName = "Doe"}
or, if you only want to pass in parameters that will actually be used, you can build a Dictionary<string,object> that contains only those parameters you need to pass in:
new Dictionary<string,object> { {"FirstName", "John" } }
I'm new to lucene.net. I want to implement search functionality on a client database. I have the following scenario:
Users will search for clients based on the currently selected city.
If the user wants to search for clients in another city, then he has to change the city and perform the search again.
To refine the search results we need to provide filters on Areas (multiple), Pincode, etc. In other words, I need the equivalent lucene queries to the following sql queries:
SELECT * FROM CLIENTS
WHERE CITY = N'City1'
AND (Area like N'%area1%' OR Area like N'%area2%')
SELECT * FROM CILENTS
WHERE CITY IN ('MUMBAI', 'DELHI')
AND CLIENTTYPE IN ('GOLD', 'SILVER')
Below is the code I've implemented to provide search with city as a filter:
private static IEnumerable<ClientSearchIndexItemDto> _search(string searchQuery, string city, string searchField = "")
{
// validation
if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", "")))
return new List<ClientSearchIndexItemDto>();
// set up Lucene searcher
using (var searcher = new IndexSearcher(_directory, false))
{
var hits_limit = 1000;
var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
// search by single field
if (!string.IsNullOrEmpty(searchField))
{
var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, searchField, analyzer);
var query = parseQuery(searchQuery, parser);
var hits = searcher.Search(query, hits_limit).ScoreDocs;
var results = _mapLuceneToDataList(hits, searcher);
analyzer.Close();
searcher.Dispose();
return results;
}
else // search by multiple fields (ordered by RELEVANCE)
{
var parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new[]
{
"ClientId",
"ClientName",
"ClientTypeNames",
"CountryName",
"StateName",
"DistrictName",
"City",
"Area",
"Street",
"Pincode",
"ContactNumber",
"DateModified"
}, analyzer);
var query = parseQuery(searchQuery, parser);
var f = new FieldCacheTermsFilter("City",new[] { city });
var hits = searcher.Search(query, f, hits_limit, Sort.RELEVANCE).ScoreDocs;
var results = _mapLuceneToDataList(hits, searcher);
analyzer.Close();
searcher.Dispose();
return results;
}
}
}
Now I have to provide more filters on Area, Pincode, etc. in which Area is multiple. I tried BooleanQuery like below:
var cityFilter = new TermQuery(new Term("City", city));
var areasFilter = new FieldCacheTermsFilter("Area",areas); -- where type of areas is string[]
BooleanQuery filterQuery = new BooleanQuery();
filterQuery.Add(cityFilter, Occur.MUST);
filterQuery.Add(areasFilter, Occur.MUST); -- here filterQuery.Add not have an overloaded method which accepts string[]
If we perform the same operation with single area then it's working fine.
I've tried with ChainedFilter like below, which doesn't seems to satisfy the requirement. The below code performs or operation on city and areas. But the requirement is to perform OR operation between the areas provided in the given city.
var f = new ChainedFilter(new Filter[] { cityFilter, areasFilter });
Can anybody suggest to me how to achieve this in lucene.net? Your help will be appreciated.
You're looking for the BooleanFilter. Almost any query object has a matching filter object.
Look into TermsFilter (from Lucene.Net.Contrib.Queries) if your indexing doesn't match the requirements of FieldCacheTermsFilter. From the documentation of the later; "this filter requires that the field contains only a single term for all documents".
var cityFilter = new FieldCacheTermsFilter("CITY", new[] {"MUMBAI", "DELHI"});
var clientTypeFilter = new FieldCacheTermsFilter("CLIENTTYPE", new [] { "GOLD", "SILVER" });
var areaFilter = new TermsFilter();
areaFilter.AddTerm(new Term("Area", "area1"));
areaFilter.AddTerm(new Term("Area", "area2"));
var filter = new BooleanFilter();
filter.Add(new FilterClause(cityFilter, Occur.MUST));
filter.Add(new FilterClause(clientTypeFilter, Occur.MUST));
filter.Add(new FilterClause(areaFilter, Occur.MUST));
IndexSearcher searcher = null; // TODO.
Query query = null; // TODO.
Int32 hits_limit = 0; // TODO.
var hits = searcher.Search(query, filter, hits_limit, Sort.RELEVANCE).ScoreDocs;
What you are looking for is nested boolean queries so that you have an or (on your cities) but that whole group (matching the or) is itself matched as an and
filter1 AND filter2 AND filter3 AND (filtercity1 OR filtercity2 OR filtercity3)
There is already a good description of how to do this here:
How to create nested boolean query with lucene API (a AND (b OR c))?