4. For sets $A$ and $B$, the union $A \cup B=\left\{a_{1}, a_{2}, a_{3}\right\}$. When $A \neq B$, $(A, B)$ and $(B, A)$ are considered different pairs. The number of such $(A, B)$ pairs is ( ).
A. 8 pairs
B. 9 pairs
C. 26 pairs
D. 27 pairs
4. D.

If $A=\left\{a_{1}, a_{2}, a_{3}\right\}$, then $B$ can be a subset of $A$, with a total of $2^{3}=8$; if $A$ is a two-element set (3 cases), for example, $A=\left\{a_{1}, a_{2}\right\}$, then $B$ is the union of $\left\{a_{3}\right\}$ and the subsets of $\left\{a_{1}, a_{2}\right\}$, with $2^{2}=4$ subsets, so there are $3 \times 4=12$ (pairs) of sets; if $A$ is a single-element set (3 cases), then $B$ has 2 subsets, and there are $3 \times 2=6$ (pairs) of sets; if $A=\varnothing$, then $B=\left\{a_{1}, a_{2}, a_{3}\right\}$, and there is 1 pair of sets. Therefore, there are a total of $8+12+6+1=27$ (pairs) of sets.