|
| 1 | +.. Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +.. or more contributor license agreements. See the NOTICE file |
| 3 | +.. distributed with this work for additional information |
| 4 | +.. regarding copyright ownership. The ASF licenses this file |
| 5 | +.. to you under the Apache License, Version 2.0 (the |
| 6 | +.. "License"); you may not use this file except in compliance |
| 7 | +.. with the License. You may obtain a copy of the License at |
| 8 | +
|
| 9 | +.. http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +
|
| 11 | +.. Unless required by applicable law or agreed to in writing, |
| 12 | +.. software distributed under the License is distributed on an |
| 13 | +.. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +.. KIND, either express or implied. See the License for the |
| 15 | +.. specific language governing permissions and limitations |
| 16 | +.. under the License. |
| 17 | +
|
| 18 | +====================== |
| 19 | +Registering Views |
| 20 | +====================== |
| 21 | + |
| 22 | +You can use the ``into_view`` method to convert a DataFrame into a view and register it with the context. |
| 23 | + |
| 24 | +.. code-block:: python |
| 25 | +
|
| 26 | + from datafusion import SessionContext, col, literal |
| 27 | +
|
| 28 | + # Create a DataFusion context |
| 29 | + ctx = SessionContext() |
| 30 | +
|
| 31 | + # Create sample data |
| 32 | + data = {"a": [1, 2, 3, 4, 5], "b": [10, 20, 30, 40, 50]} |
| 33 | +
|
| 34 | + # Create a DataFrame from the dictionary |
| 35 | + df = ctx.from_pydict(data, "my_table") |
| 36 | +
|
| 37 | + # Filter the DataFrame (for example, keep rows where a > 2) |
| 38 | + df_filtered = df.filter(col("a") > literal(2)) |
| 39 | +
|
| 40 | + # Convert the filtered DataFrame into a view |
| 41 | + view = df_filtered.into_view() |
| 42 | +
|
| 43 | + # Register the view with the context |
| 44 | + ctx.register_table("view1", view) |
| 45 | +
|
| 46 | + # Now run a SQL query against the registered view |
| 47 | + df_view = ctx.sql("SELECT * FROM view1") |
| 48 | +
|
| 49 | + # Collect the results |
| 50 | + results = df_view.collect() |
| 51 | +
|
| 52 | + # Convert results to a list of dictionaries for display |
| 53 | + result_dicts = [batch.to_pydict() for batch in results] |
| 54 | +
|
| 55 | + print(result_dicts) |
| 56 | +
|
| 57 | +This will output: |
| 58 | + |
| 59 | +.. code-block:: python |
| 60 | +
|
| 61 | + [{'a': [3, 4, 5], 'b': [30, 40, 50]}] |
0 commit comments