elasticsearch php nested aggregations - php

I tried searching an trying.
I need to group the nested fields.
The sql query is as follows:
SELECT p_application_category,
Sum(p_recv_bytes) as download,
p_date
FROM ZLog2 $w
group by p_application_category;

I solved the problem with elastic sql plugin. It makes regular sql statements available in elastic.

Related

Is there a way to add a LIMIT to an UPDATE query in Doctrine ORM?

I am using Doctrine 2.5.x and I am having problems with getting the LIMIT clause to work for UPDATE queries. It always updates all matched records (i.e. it seems to ignore the LIMIT clause).
setMaxResults() seems to have no effect when used together with UPDATE queries.
As a quick workaround I am using a native MySQL query but that cannot be the best solution.
I tried these examples but none are working:
Doctrine update query with LIMIT
https://recalll.co/app/?q=doctrine2%20-%20Doctrine%20update%20query%20with%20LIMIT
QueryBuilder with setMaxResults() (does not work):
$qb = $em->createQueryBuilder();
$query = $qb->update('\Task\Entity', 't')
->set('t.ClaimedBy', 1)
->where('t.Claimed IS NULL')
->getQuery();
$query->setMaxResults(20);
$this->log($query->getSQL());
Hope someone can help in finding a better solution than a native query. It takes away the whole benefit of the ORM.
Is it even possible to use a LIMIT clause in an UPDATE statement?
In short, no, because the SQL specification does not support UPDATE ... LIMIT ..., so none of the ORM trying to achieve portability should allow you to do it.
Please also have a look at MySQL Reference Manual itself stating that UPDATE ... LIMIT ... is not a standard SQL construction:
MySQL Server supports some extensions that you probably will not find in other SQL DBMSs. Be warned that if you use them, your code will not be portable to other SQL servers. In some cases, you can write code that includes MySQL extensions, but is still portable, by using comments of the following form:
SQL statement syntax
The ORDER BY and LIMIT clauses of the UPDATE and DELETE statements.
So by essence because what you are trying to achieve is not standard SQL the ORM will not have a portable way to implement it and will probably not implement it at all.
Sorry, but what you are trying to achieve is not possible through DQL, because:
Ocramius commented on Sep 2, 2014
DQL doesn't allow limit on UPDATE queries, as it is not portable.
As suggested in this issue of DoctrineBundle repository by its owner, Marco Pivetta (he also happen to be the owner of the ORM repository).
Further information, although it might needs a good link to the right ISO specification documentation that is sadly not freely available:
The ISO standard of UPDATE instruction do not allow LIMIT in an UPDATE, where SELECT is, of course, an instruction that does allow it.
As you were raising it by yourself, the purpose of an ORM is to not write pure SQL in order to have it cross DBMS compatible. If there is no possibility to make it that way, then it makes sense that the ORM does not implement it.
Also note that on other SQL variant than MYSQL, the limit is actually part of the SELECT clause:
select * from demo limit 10
Would translate in a SQL Server to
select top 10 from demo
Or in Orcale to
select * from demo WHERE rownum = 1
Also see: https://stackoverflow.com/a/1063937/2123530
As b.enoit.be already stated in his answer, this is not possible in Doctrine because using LIMIT's in an UPDATE statement is not portable (only valid in MySQL).
Hope someone can help in finding a better solution than a native query. It takes away the whole benefit of the ORM.
I would argue that you are mixing business rules with persistence (and the ORM does not play well with that, luckily).
Let me explain:
Updating an entity's state is not necessarily a business rule. Updating max. 20 entities is (where does that 20 come from?).
In order to fix this, you should properly separate your business rules and persistence by separating it into a service.
class TaskService
{
private $taskRepository;
public function __construct(TaskRepository $taskRepository)
{
$this->taskRepository = $taskRepository;
}
public function updateClaimedBy()
{
$criteria = ['Claimed' => null];
$orderBy = null;
// Only update the first 20 because XYZ
$limit = 20;
$tasks = $taskRepository->findBy($criteria, $orderBy, $limit);
foreach($tasks as $task) {
$task->setClaimedBy(1)
}
}
}

Having trouble while searching in mysql via REGEXP

I am implementing search in my project so I have to search data which will be in any order so I'm following this question. But my query was not working
my php query is
$cat="(?=.*Women)(?=.*Rings)";
$sql="select * from tbl_jewellery where categories RLike '$cat';";
when I change regex to Women.*Ring|Ring.*Women
It works fine but (?=.*Women)(?=.*Rings) approach is easy and can be used for multiple words just adding them.
MySQL does not implement (? syntax in REGEXPs. I think MariaDB 10.0.5 does.
For a significant subset of such queries, you could use a FULLTEXT index on that categories with this:
MATCH(categories)
AGAINST('+women +rings' IN BOOLEAN MODE)
That says both "words" occur, without limitations on order or proximity.

Builder for ElasticSearch query DSL in Yii2 (or standalone)

As far as I can see, the only way to make a query to ElasticSearch in Yii2 is to run ElasticModel::find()->query($query), where $query is a complex array containing the actual query written in ElasticSearch query DSL.
The query is huge and quickly becomes unmanageable. For SQL Yii2 provides a powerful query builder class that supports tons of useful methods like andWhere(). For ElasticSearch everything goes into one gigantic query expression, very much like building an SQL expression string by hand.
Is there any high-level wrapper for ElasticSearch query DSL for Yii2? If not, is there a standalone library with similar functionality?
If you intend to build for version 1.6 of elastic, I have created a query builder for my company and published it here
You will use it as a standalone query builder, and at the end you will need to get the final query array and pass it to the query executer.
To install it, you can simply use composer composer require itvisionsy/php-es-orm or download the zipped version here.
The link above contains some examples, and here is a copy:
//build the query using different methods
$query = \ItvisionSy\EsMapper\QueryBuilder::make()
->where('key1','some value') //term clause
->where('key2',$intValue,'>') //range clause
->where('key3','value','!=') //must_not term clause
->where('key4', ['value1','value2']) //terms clause
->where('email', '#hotmail.com', '*=') //wildcard search for all #hotmail.com emails
->sort('key1','asc') //first sort option
->sort('key2',['order'=>'asc','mode'=>'avg']) //second sort option
->from(20)->size(20) //results from 20 to 39
->toArray();
//modify the query as you need
$query['aggs']=['company'=>['terms'=>['field'=>'company']]];
//then execute it against a type query
$result = TypeQuery::query($query);
//i am not sure about Yii way to execute, according to the question, it should be:
$result = ElasticModel::find()->query($query);
The package also include a simple ElasticSearch ORM class which maybe useful for you. Take a look at it here.
Hope this helps you...

Query a Query - MySQL and PHP

I was recently trying to do a project*, which caused me to ask this question. Although since then I've found an alternative solution, I am still curious if what I envisioned doing is, in any way, possible.
Essentially, I am wondering if there is anyway to perform a MySQL query on a MySQL query result in php. For example:
$result = mysql_query("SELECT * FROM foo WHERE bar=".$barValue);
AND THEN, be able to perform multiple queries on $result:
$newResult = mysql_query("SELECT * FROM $result WHERE otherBar=".$barValue);
OR
$otherNewResult = mysql_query("SELECT * FROM $result WHERE otherOtherBar=".$barValue." ORDER BY foobar ASC");
AND so on and so forth...
I realize that I could append the original query with my new WHERE statements and ORDER BYs, but that causes my to query the database unnecessarily and it prevents me from writing more objected oriented code (because I can't pass around a result to be queried, but rather have to requery the database in every function...)
Any advice, pieces of code, frameworks, or ramblings appreciated.
*BTW, my project was having to query a large database of people for people born in certain age groups and then query those age groups for different demographics.
Edit
No, writing a custom function to query the database is not worth the object-orientation (and modifiability) it would give me
You could do a nested query in the same SQL query and keep PHP out of it:
'SELECT * FROM (SELECT * FROM foo WHERE bar="something") AS q1 WHERE q1.bar2 = "something else"'
The question has already been answered. However following explanation will help someone who might be interested in knowing the details of it.
What are Nested query / subquery:
Subqueries are also known as nested queries. A subquery is a SELECT statement within another statement. MySQL supports all SQL standards and additionally provides MySQL specific features.
Why should I use Subquery:
Subquery is structured and it is possible to isolate each parts of statement
Subquery is more readable that complex joins and unions
Subquery provides alternative means to perform action which otherwise would require complex joins and unions
What Subquery returns:
A subquery can return a single value, a single row, a single column, or a table. These are called scalar, column, row, and table subqueries.
Reference: http://dev.mysql.com/doc/refman/5.7/en/subqueries.html
http://www.w3resource.com/sql/subqueries/nested-subqueries.php

php mysql combine queries

If I have 2 mysql_query commands in a single php file, is their a way to combine them?
For example, I have:
$a=mysql_query(SELECT * FROM table1);
$b=mysql_query(SELECT id FROM table3);
but I want to combine them into a single mysql_query, would this be more efficient? would it be faster?
multiple queries are not supported in mysql_query as descripted on php manual, so you can't combine both query in php mysql_query way
Here is another good reference from php manual notes:
Executed with multiple queries at
once, the mysql_query function will
return a result only for the first
query. The other queries will be
executed as well, but you won't have a
result for them.
UNION should work (MySQL Manual)
SELECT id FROM table1 UNION SELECT id FROM table3;
Edit:
I see: You want all ("*") from table1. This is a little bit more difficult, but UNION may help also. However, you are really sure you want to do this? Is there any relationship beetween those two tables, or should this just be a kind of micro optimization?

Categories