Esper Learning Eight: EPL grammar (iv)

Source: Internet
Author: User
Tags constant constructor int size one table sort first row lenovo

Reprint Please specify source: Http://blog.csdn.net/luonanqin



National Day holiday after the work week, incredibly bitter force only a day off, blog did not write not to say, play also the foot to twist. Not only that, this week started crazy overtime, so today this article dragged and dragged ...

About EPL, has written three, pre-estimated a bit, in addition to today's article, there are about 5 later. Don't be too much, the official document to EPL of the explanation of nearly 140 pages, I have tried to kill all the nonsense, and then with my attached example, see my 10 article is more comfortable than the 140 pages of English documents. Please forgive me for the speed of a week, after all, I still have to study, life, work, one can not be less.

Today's commentary includes three pieces: Order By,limit,insert into. People will SQL should be familiar with these three things, the first two is relatively simple, Insert into will have some differences, more space.


1.Order by

EPL's order by is almost exactly the same as SQL, and the effect is to sort the output results, but there are some areas to be aware of. The syntax is as follows:

ORDER BY expression [ASC | desc] [, expression [ASC | desc]] [, ...]

Expreession represents the field to sort, ASC indicates ascending (from small to large), and DESC indicates descending order (from large to small). As an example:

Output each entry to 5 events, and first in ascending order by name, and then in descending order of age.
SELECT * from User output every 5 events order by name, age desc
The use of the method is very simple, in addition to the same characteristics as SQL, but also his own points to note:

A. If you do not specifically specify ascending or descending, by default it is sorted in ascending order.

B. If an aggregate function appears in the clause of an order BY, the aggregate function must appear in the clause of the SELECT.

C. expression that appears in select or expression defined in select is also valid in order by.

D. If the order by is in a sentence that does not have a join or a group by, the sort result is idempotent, otherwise it is not idempotent.


2. Limit

The limit is essentially the same in EPL and in SQL, although SQL uses a specific number to represent the limiting range, while EPL can be a constant or variable to represent the limit. The syntax is as follows:

Limit Row_count [offset offset_count]
Row_count indicates how many rows are output, either an integer constant or an integer variable to facilitate runtime modification.

Offset_count indicates that n-rows are skipped in the current result set and then output, as well as an integer variable. If you do not use this parameter, it means that 0 rows are skipped, which is the output from the first row. Examples are as follows:

Output result set line 3rd through 10th
Select URI, COUNT (*) from webevent GROUP by URI output snapshot every 1 minute order by Count (*) des C Limit 8 Offset 2
In addition to the syntax above, limit has a simplified notation, which is actually a reference to the SQL standard.

Limit offset_count[, Row_count]
The two parameters have the same meaning as above, and we'll rewrite the example above:

Output result set line 3rd through 10th
Select URI, COUNT (*) from webevent GROUP by URI output snapshot every 1 minute order by Count (*) des C Limit 2, 8
What if this two parameter is a negative number?

Row_count is negative, the unrestricted output, if 0, is not output. When Row_count is a variable representation and the variable is NULL, the output is unrestricted.

Offset _count is not allowed for negative numbers, and if the variable is represented, and the value of the variable is null or negative, then EPL will assume that he is 0.


3. Insert into

3.1 Simple usage

EPL insert into and SQL have a big difference. SQL is inserting data into one table, and EPL is putting the results of an event stream into another stream of events, which can then be computed for another event stream. So one of the benefits of INSERT into is that it is possible to cascade the results of an event stream into a scenario where the result data of the previous business needs to be placed in the next business process. In addition, Insert into also has the effect of merging multiple calculations. Come here to believe that we have been more and more curious about him, not urgent, we first look at the syntax:

Insert [IStream | irstream | rstream] into event_stream_name [(Property_name [, Property_name])]

Event_stream_name defines the name of the event stream, and after executing the INSERT definition, we can use Select to perform other calculations on the event stream.

IStream | Irstream | Rstream indicates that the event stream allows input/input and output/output data for another event to enter (the explanation seems to be very round.) A moment to see the example will understand)

Property_name represents the name of the attribute contained in the event stream, separated by commas between multiple property names, and enclosed in parentheses.

The above instructions may not be very well understood, let's look at an example:

The newly entered ASUS event is passed to computer, and the cid,csize of ASUS Id,size and computer corresponds to
insert into computer (cid,csize) Select Id,size from ASUS

//second notation
INSERT into computer Select ID as CID, size as CSize Asus
As you can see from the example, insert into needs to be used with select to indicate which of the previous event flows will go into the event stream defined by insert into. And the fields in the select are to correspond to the attributes of the event stream in the insert (this refers to the corresponding data type, and the number of attributes must be the same). If the name of the event stream defined by insert has been previously defined (except as defined in INSERT into), the names are not allowed.

I personally recommend the second way, the alias that is set through as is the attribute of the event stream defined by the insert, which avoids the error of inconsistent number of attributes.


Just said IStream | Irstream | The use of Rstream may be somewhat unclear, here is a complete example.

/** * * @author luonanqin * * * */class Asus {private int id;

	private int size;
	public int getId () {return id;
	} public void setId (int id) {this.id = ID;
	} public int GetSize () {return size;
	} public void setSize (int size) {this.size = size;
	} public String toString () {return ' ID: ' + id + ', size: ' + size; }} class Insertrstreamlistener implements Updatelistener {public void update (eventbean[] newevents, eventbean[] Oldev Ents) {if (newevents! = null) {for (int i = 0; i < newevents.length; i++) {Object id = newevents[i].g
				ET ("CID");
			System.out.println ("Insert asus:cid:" + ID); }} if (oldevents! = null) {for (int i = 0; i < oldevents.length; i++) {Object id = oldevents[i].get (
				"CID");
			System.out.println ("Remove asus:cid:" + ID);
	}} System.out.println (); }} public class Insertrstreamtest {public static void main (string[] args) throws Interruptedexception {Epservicepr OviDer Epservice = Epserviceprovidermanager.getdefaultprovider ();

		Epadministrator admin = epservice.getepadministrator ();
		String asus = Asus.class.getName ();
		String Insertepl = "Insert Rstream into computer (cid,csize) Select id,size from" + Asus + ". Win:length (1)";

		String insertselectepl = "Select Cid from Computer.win:length_batch (2)";
		Epstatement state = Admin.createepl (INSERTEPL);
		Epstatement state1 = Admin.createepl (INSERTSELECTEPL);

		State1.addlistener (New Insertrstreamlistener ());

		Epruntime runtime = Epservice.getepruntime ();
		ASUS APPLE1 = new Asus ();
		Apple1.setid (1);
		Apple1.setsize (1);
		System.out.println ("Send Asus:" + apple1);

		Runtime.sendevent (APPLE1);
		ASUS Apple2 = new Asus ();
		Apple2.setid (2);
		Apple2.setsize (1);
		System.out.println ("Send Asus:" + apple2);

		Runtime.sendevent (Apple2);
		ASUS APPLE3 = new Asus ();
		Apple3.setid (3);
		Apple3.setsize (3);
		System.out.println ("Send Asus:" + apple3);

		Runtime.sendevent (APPLE3); Asus Apple4 = new Asus ();
		Apple4.setid (4);
		Apple4.setsize (4);
		System.out.println ("Send Asus:" + apple4);

		Runtime.sendevent (APPLE4);
		ASUS APPLE5 = new Asus ();
		Apple5.setid (5);
		Apple5.setsize (3);
		System.out.println ("Send Asus:" + apple5);

		Runtime.sendevent (APPLE5);
		ASUS APPLE6 = new Asus ();
		Apple6.setid (6);
		Apple6.setsize (4);
		System.out.println ("Send Asus:" + apple6);
	Runtime.sendevent (APPLE6); }
}
Execution Result:

Send Asus:id:1, size:1
send Asus:id:2, size:1
send Asus:id:3, size:3
insert asus:cid:1
Insert A Sus:cid:2

send Asus:id:4, size:4
send Asus:id:5, size:3
insert asus:cid:3
Insert Asus:cid:4
  send Asus:id:6, Size:4
In this example, INSERTEPL indicates that when the Asus event is removed from the length 1 view, the removed event is put into computer. INSERTSELECTEPL is the calculation of the computer's event stream, which only outputs the CID for each event when it enters two events. The performance of Rstream here shows that, after entering an event with an ID of 1 2 3, the listener of INSERTSELECTEPL is triggered, because events with IDs 1 and 2 are removed after sending the Asus ID 2 and 3 events. After entering the computer and satisfying the length=2, the listener sees events with IDs 1 and 2 entering the computer.

If the specified Rstream is not displayed, insert into allows only the IStream event stream to enter computer. If specified as Irstream, the incoming and removed ASUS will go to computer.


The above example specifies what attributes the insert into event stream will have, if not specified. Please look at the example:

INSERT INTO computer SELECT * from Asus
It is easy to think of the fact that the Asus event that enters the engine is actually passed into the computer defined event stream, and that the property is exactly like Asus, which can be said to be a duplicate version of Asus, except for the name. Perhaps some people think this is not interesting, directly calculate the Asus event stream is not OK, in fact, when the business process data, this practice can block out the external data sources, to achieve the isolation of the business layer.

Assuming that Asus also contains other JavaBean, it is also possible to pass the bean's data to another event stream. Examples are as follows:

Lenovo contains ThinkPad this javabean insert into
computer select thinkpad.* from Lenovo


3.2 Merge Event Stream

Insert into takes the event of a stream and also supports merging of multiple streams. In layman's terms, the merged stream data must be consistent to be merged. And after the first definition of the insert's event flow, the other event streams would have to be merged to correspond to the previously defined number of attributes and data types. Examples are as follows:

Define the computer and insert the Asus data input into the
computer (CID, csize) Select aid,asize from ASUS

// Based on the previous computer definition, the properties of Lenovo are entered into the
insert into computer (CID, csize) select Lid,lsize from Lenovo
If you select multiple event streams, but you only want to enter one, you should write as follows:
INSERT INTO computer Select l.* from Asus as a, Lenovo as L
In addition, EPL supports calling function conversion events and then entering insert into:
Convert Lenovo event after input computer
insert INTO computer select Converter.convert (L) from Lenovo as L
Note that using a custom function must return Javabean,map, or an object array, and cannot use as to set the alias for the converted result.


3.3 Decorated Events

What you've seen before is not to insert the event stream as a whole, but to input some of the properties of the event stream into insert. You can actually put a complex expression that consists of an event flow overall and an event flow property into an insert. Examples are as follows:

INSERT INTO computer SELECT *, Size*price as SP from Asus
///The first * represents the multiplication of Asus,size*price *, the two do not affect each other
If another event stream wants to enter this insert, then the event stream property must be the same as all the properties that are represented by the first *.


3.4 Event Objects instantiated by insert into

In all previous examples, the event structure for insert into is defined with the SELECT clause in the INSERT clause. If we want to use an already defined event structure. The answer is yes. However, if the event is JavaBean and is not registered with the engine in advance, you will need to write the full name of the class in the INSERT clause. For example:

Insert INTO Test.computer.Computer ...
Of course, if you have registered before using it, it is also possible to use the name of the registration.

Because the event structure is long-defined, it is necessary to conform to the properties of the Insert event when writing a select, and if the attribute name is not the same as the alias, the same can be used without setting the alias, and the data type must correspond. For example:

Computer contains CID and CSize attributes
insert into Test.computer.Computer Select Aid as CID, asize as CSize from Dell
But this usage is less necessary when the computer has a construction method that contains parameters. Let's look at a complete example, and you'll probably understand.

/** * * @author luonanqin * * * */class Car {private int size;
	private String name;

	private int price;
	public void setSize (int size) {this.size = size;
	} public void SetName (String name) {this.name = name;
	} public void Setprice (int price) {this.price = Price;
	} public int GetSize () {return size;
	} public String GetName () {return name;
	} public int GetPrice () {return price;
	}} class Auto {private int autoSize;

	Private String Autoname;
		Public Auto (int s, String n) {this.autosize = s;
	This.autoname = n;
	} public String toString () {return "AutoSize:" + AutoSize + ", Autoname:" + autoname;
	}} class Benz {private int benzsize;

	Private String Benzname;
	public void setbenzsize (int benzsize) {this.benzsize = benzsize;
	} public void Setbenzname (String benzname) {this.benzname = Benzname;
	} public String toString () {return "benzsize:" + benzsize + ", Benzname:" + benzname; }} class InstantiatepoPulatelistener implements Updatelistener {public void update (eventbean[] newevents, eventbean[] oldevents) {if (newe
			Vents! = null) {Object car = newevents[0].getunderlying ();
		SYSTEM.OUT.PRINTLN (car); }}} public class Instantiatepopulatetest {public static void main (string[] args) throws Interruptedexception {EP

		ServiceProvider Epservice = Epserviceprovidermanager.getdefaultprovider ();

		Epadministrator admin = epservice.getepadministrator ();
		String car = Car.class.getName ();
		String auto = Auto.class.getName ();

		String Benz = Benz.class.getName ();
		String Carttoautoepl = "INSERT INTO" + Auto + "Select size, name from" + car;
		String AUTOEPL = "SELECT * from" + auto;
		String Carttobenzepl = "INSERT into" + Benz + "Select Size as Benzsize, name as Benzname from" + car; String benzEpl2 = "INSERT into" + Benz + "(benzsize,benzname) Select size, name from" + car;
		String BENZEPL = "SELECT * from" + Benz;
ADMIN.CREATEEPL (CARTTOAUTOEPL); Epstatement state1 = Admin.createepl (AUTOEPL); State1.addlistener (new Instantiatepopulatelistener ()); ADMIN.CREATEEPL (CARTTOBENZEPL); Epstatement State2 = Admin.createepl (BENZEPL); State2.addlistener (new Instantiatepopulatelistener ()); Epruntime runtime = Epservice.getepruntime (); Car C1 = new car (); c1.setsize (1); C1.setname ("car1"); C1.setprice (one); Runtime.sendevent (C1); Car C2 = new car (); c2.setsize (2); C2.setname ("car2"); C2.setprice (runtime.sendevent);}} Execution Result:

Autosize:1, Autoname:car1
benzsize:1, benzname:car1
autosize:2, autoname:car2
benzsize:2, Benzname:car 2
The execution results here are easy to understand, and the key is to Cartoautoepl and cartobenzepl two sentences.

For Auto's JavaBean, we can find that it contains a constructor with parameters and no property corresponding to the Set method, in Cartoautoepl, the content of select does not correspond to the property name. This is really true, because Auto has a constructor that contains parameters, so that select can write more arbitrarily. However, it is important to remember that the order of the parameters in the constructor must correspond to the data type of the attribute in the Select, and if the name and size are swapped here, it will be an error.

For Benz's JavaBean, you can see that each property has a corresponding set method and no constructor with a parameter, so the name of the property in select requires as to set the alias. Of course, like BENZEPL2, you can also avoid setting aliases in select.


In a nutshell, if you have a constructor with a parameter in JavaBean, you do not need to display the name of the attribute in EPL. If there is no constructor, then the set method must be included, and the specific property is written in select. Each of these kinds of writing has its own advantages, which can be used selectively for specific situations.


Today's content is generally more relaxed, insert into is also the focus of today, I hope everyone to study well, the use is very big drop has oh.

PS: Recent project tense, even Saturday also have to work overtime, so may be two weeks out of an article, also ask you understand.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.