Mysql json field and algolia - algolia

i want to add this table to the algolia:
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| data | json | NO | | NULL | |
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
+-------+------------------+------+-----+---------+----------------+
there is only one row on this table and content of data is:
[
{
"id":"7cc481e3eab24b4ef9ccc945c00f7784",
"desc":"shirts desc",
"name":"Shirts",
"slug":"shirts",
"image":"7cc481e3eab24b4ef9ccc945c00f7784.jpeg",
"categories":[
]
},
{
"id":"67d188521fa8531dd3e2044814cb942342",
"desc":"some desc",
"name":"Jackets",
"slug":"jackets",
"image":"67d188521fa8531dd3e2044814cb942342.jpeg",
"categories":[
{
"id":"671a83b87369ee6773774c0d6d4455e2",
"desc":"sealed desc",
"name":"Sealedq",
"slug":"sealedq",
"image":""
}
]
},
{
"id":"ad03b6be35714f7bb7f2ecc82d512c79",
"desc":"some desc",
"name":"Trousers",
"slug":"trousers",
"image":"ad03b6be35714f7bb7f2ecc82d512c79.jpg"
},
{
"id":"ea265cbc18db7ad6b3a3013af3070890",
"desc":"some desc",
"name":"Sweaters",
"slug":"sweaters",
"image":"ea265cbc18db7ad6b3a3013af3070890.jpeg"
}
]
these all work with Laravel 5.2,
when i send these data to algolia, it will create only one record and set objectID to id of table.
How can i send only data field to algolia and set id of data field as objectID?
i use this code for just to test and it works for me, but i think this is not the right way, maybe i should use Synonyms.
$client = new AlgoliaSearch\Client("AppID", "AdminKey");
$index = $client->initIndex('catalog');
$results = Model::select('data')->first();
$results = json_decode($results->data, true);
if ($results)
{
$batch = array();
// iterate over results and send them by batch of 10000 elements
foreach ($results as $row)
{
// select the identifier of this row
$row['objectID'] = $row['id'];
array_push($batch, $row);
}
return $index->saveObjects($batch);
}

How can i send only data field to algolia and set id of data field as objectID?
i use this code for just to test and it works for me, but i think this is not the right way, maybe i should use Synonyms.
Parsing the content of the data on your side and adding it to the object is the right way to go. I don't know the PHP framework you're using but you can probably do something like:
$batch = array();
$rows = Model::select('*')->all();
foreach ($rows as $row) {
$row['objectID'] = $row['id']
$row['data'] = json_decode($row['data'], true);
array_push($batch, $row);
}
$index->saveObjects($batch);
Synonyms are used for something else. You can read more here

Related

Split PSCustomObjects in to strings/array

Hi I have n sum of objects for each Node like this:
NodeName : 11111
System.AreaId : 2375
System.AreaPath : Project
System.TeamProject : Project
System.NodeName : Project
System.AreaLevel1 : Project
Every node can have different objects in it.
How can I split them to an arrays/strings without specifying the object name so I can create foreach separate object loop?
mklement0 beat me to what I was going to post. Since I have the code drafted already I will post it.
Like mklement0 said in comments, you can access object properties through use of .psobject.Properties. Below in the code I am using a switch statement to check if an object contains a specific property.
$objs = #(
[pscustomobject]#{
AreaId = 2375
AreaPath = ''
TeamProject = 'Project2'
NodeName = ''
AreaLevel1 = ''
},
[pscustomobject]#{
AreaId = 342
AreaPath = ''
TeamProject = 'Project2'
Color = 'Red'
}
)
switch ($objs) {
{ $_.psobject.properties.name -contains 'Color' } {
'Object contains Color property'
}
{ $_.psobject.properties.name -contains 'NodeName' } {
'Object contains NodeName property'
}
Default {}
}

Tidying up a powershell script

So I need help tidying up a script that I have. The purpose of this script is to make 18 different sql files based on the data below 18 different column headers. What my script does now is make 1 sql file based on which column I choose to input via "Read-Host". This is my current script
function get-header
{Read-Host "Type the Column header betwen B-Z for which sql files needs to be created"
}
function get-column
{
Read-Host "Type the Column number"
}
do
{
$val = get-header
}
while(!($val))
do
{$col = get-column
}
while(!($col))
switch ($val)
{
"B"{$column = "1"}
"C"{$column = "2"}
"D"{$column = "3"}
"E"{$column = "4"}
"F"{$column = "5"}
"G"{$column = "6"}
"H"{$column = "7"}
"I"{$column = "8"}
"J"{$column = "9"}
"K"{$column = "10"}
"L"{$column = "11"}
"M"{$column = "12"}
"N"{$column = "13"}
"O"{$column = "14"}
"P"{$column = "15"}
"Q"{$column = "16"}
"R"{$column = "17"}
"S"{$column = "18"}
"T"{$column = "19"}
"U"{$column = "20"}
"V"{$column = "21"}
"W"{$column = "22"}
"X"{$column = "23"}
"Y"{$column = "24"}
"Z"{$column = "25"}
default { $column = 'Unknown' }
}
if ($column -eq 'Unknown')
{
Write-Warning "Not a valid input"
return
}
$csv = Import-Csv "Indices Updates - September 2018.csv" -Header 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
$date = (Get-Date -Format "MM/dd/yyyy").Replace("-","/")
$sql = #("INSERT INTO benchmark_values(created_at,benchmark_id,date,amount,created_by_username)
foreach($data in $csv)
{
$secondcolumn = [int]$column + 1
$sql += "('$date',$col,'$($data.1)',$($data.$secondcolumn),'BPylla'),"
}
$sql | Out-File "sqldata.sql"
Now I want to get rid of read-host entirely because I dont want to input any values. I also will give an example of what the csv file looks like and what the sql file should look like.
So the goal is to produce different sql files from each column of information using the the sql format posted. I already have the template for that in my script now, I just need the script to create all the sql files based on headers and still input the data below the headers in the new sql files. Any help would be greatly appreciated! Thanks!

Sort and delete duplicates in multidimensional array

I have an multidimensional Array and want to sort it by the date and delete the duplicate entries (by date).
$arrayPlaces = [System.Collections.ArrayList]#()
and that is how the Array looks like:
$arrayPlaces.Add(($mailBarcodeInformation[2], $mailScannedStart.Substring(22), "", "", "", "", "", ""))
The empty fields are filled later. The second field $mailScannedStart.Substring(22) is the time and the Array should be sorted by that and the duplicates should also be removed.
I searched a lot but couldn't find any help.
A common approach is to add a custom object into an array and use the buit-in cmdlet sort -unique. It's much more readable:
$arrayPlaces = [System.Collections.ArrayList]#()
#.........
$arrayPlaces.Add([PSCustomObject]#{
barcode = $mailBarcodeInformation[2]
time = $mailScannedStart.Substring(22)
foo1 = ''
foo2 = ''
foo3 = ''
}) >$null
#...........
$sorted = $arrayPlaces | sort time -Unique
However, since you already use a .NET class you can switch to a fast .NET SortedDictionary, which automatically sorts and deduplicates the collection when items are added:
$arrayPlaces = [Collections.Generic.SortedDictionary[string,array]]#{}
Adding and overwriting the old value:
$key = $mailScannedStart.Substring(22)
$arrayPlaces[$key] = $mailBarcodeInformation[2], $key, "", "", "", "", "", ""
Checking for presence of an item using its key:
if ($arrayPlaces.ContainsKey($key)) { ....... }
Removing:
[void]$arrayPlaces.Remove('foo')
Accessing:
$items = $arrayPlaces['foo']
$item = $arrayPlaces['foo'][0]
Enumerating (faster):
foreach ($items in $arrayPlaces.Values) {
# .........
}
Enumerating/pipelining (slower):
$arrayPlaces.Values | foreach { $_[0] = $_[1] + $[2] }

How can I use references with Perl6::Form?

I'm trying to print tabular data with Perl6::Form, but I'm not sure how to output data from hash references. Here's what I tried so far:
#!/usr/bin/perl
use Perl6::Form;
my #alerts;
push #alerts, { site => "192.168.0.1", status => "200", id => "QWE" };
push #alerts, { site => "192.168.0.2", status => "500", id => "QER" };
print form
' ====================================== ',
'| ID | SITE | STATUS |',
'|-------------+------------+-----------|',
'| {[[[[[[[[[} |{[[[[[[[[[} | {>>>>>>>} |',
\#alerts{id}, \#alerts{site},\#alerts{status},
' ====================================== ';
You need parallel arrays.
my #ids = map { $_->{id} } #alerts;
my #sites = map { $_->{site} } #alerts;
my #statuses = map { $_->{status} } #alerts;
print
form
'+=======================================+',
'| ID | SITE | STATUS |',
'|-------------+-------------+-----------|',
'| {[[[[[[[[[} | {[[[[[[[[[} | {>>>>>>>} |',
\#ids, \#sites, \#statuses,
'+=======================================+';
We can eliminate the code duplication.
my %dbf; # Data by field
for my $field (qw( id site status )) {
$dbf{$field} = [ map { $_->{$field} } #alerts ];
}
print
form
'+=======================================+',
'| ID | SITE | STATUS |',
'|-------------+-------------+-----------|',
'| {[[[[[[[[[} | {[[[[[[[[[} | {>>>>>>>} |',
$dbf{id}, $dbf{site}, $dbf{status},
'+=======================================+';

Postgresql lowercase to compare data

I want to get the contents from a row in the Postgresql database and compare the lowercase version of it to a lowercase version of a user input to check if it exists in the database.
i tried:
"SELECT LOWER(name) FROM user_names WHERE name LIKE '%$search%' ORDER BY name ASC"
but that make query not working at all.
EDIT
I am trying to implement an autocomplete Jquery UI like here:
http://jqueryui.com/demos/autocomplete/#remote
for search box (for names)
using javascript and php.
php code:
$search = ($_GET['term']);
if (!$con)
{ die('Could not connect: ' . pg_last_error ());}
else
{
$sql = "SELECT name FROM users_table WHERE name LIKE '%$search%' ORDER BY name ASC";
$result = pg_query($sql);
$json = '[';
$first = true;
while ($row = pg_fetch_array($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
exit();
}
JavaScript code:
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./file.php",
minLength: 3
})
})
all above work great.. exactly like in Demo here: http://jqueryui.com/demos/autocomplete/#remote
my problem is that the names in database stored in Uppercase (e.g. LORI)
and of course the user prefers to insert a lowercase in search box to search for name (e.g. lori). but since it stored in uppercase, i need to convert it.
i tried as your suggestion :
$sql = "SELECT LOWER(name) FROM users_table WHERE name ILIKE '%$search%' ORDER BY name ASC";
then i got an empty drop down list!
pretty weird!
thanks in advance.
Google is your friend:
SELECT LOWER(name) FROM user_names
WHERE name ILIKE '%$search%' ORDER BY name ASC